Android 啟動後台運行程式(Service)

來源:互聯網
上載者:User

Android開發中,當需要建立在後台啟動並執行程式的時候,就要使用到Service。Service 可以分為有無限生命和有限生命兩種。特別需要注意的是Service跟Activities是不同的(簡單來說可以理解為後台與前台的區別),例如,如果需要使用Service的話,需要調用startService(),從而利用startService()去調用Service中的OnCreate()和onStart()方法來啟動一個背景Service。
      啟動一個Service的過程如下:context.startService()  ->onCreate()- >onStart()->Service running其中onCreate()可以進行一些服務的初始化工作,onStart()則啟動服務。
      停止一個Service的過程如下:context.stopService() | ->onDestroy() ->Service stop
      接下來的執行個體是一個利用後台服務播放音樂的小例子,點擊start運行服務,點擊stop停止服務。
ServicesDemo.java(是一個Activity)

package com.android.myservice;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class ServiceDemo extends Activity implements OnClickListener {    private static final String TAG = "ServiceDemo";    Button buttonStart, buttonStop;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        buttonStart = (Button) findViewById(R.id.buttonStart);        buttonStop = (Button) findViewById(R.id.buttonStop);        buttonStart.setOnClickListener(this);        buttonStop.setOnClickListener(this);    }    public void onClick(View src) {        switch (src.getId()) {            case R.id.buttonStart:                Log.i(TAG, "onClick: starting service");                startService(new Intent(this, MyService.class));                break;            case R.id.buttonStop:                Log.i(TAG, "onClick: stopping service");                stopService(new Intent(this, MyService.class));                break;        }    }}

除此之外還要在Manifest裡面聲明服務:(AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.android.myservice">    <application android:label="@string/app_name">        <activity android:name=".ServiceDemo" android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN"/>                <category android:name="android.intent.category.LAUNCHER"/>            </intent-filter>        </activity>        <service android:enabled="true" android:name=".MyService"/>    </application></manifest>

定義Service(MyService.java)

package com.android.myservice;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MyService extends Service {    private static final String TAG = "MyService";    MediaPlayer player;    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        Toast.makeText(this, "My Service created", Toast.LENGTH_LONG).show();        Log.i(TAG, "onCreate");        player = MediaPlayer.create(this, R.raw.braincandy);        player.setLooping(false);    }    @Override    public void onDestroy() {        Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();        Log.i(TAG, "onDestroy");        player.stop();    }    @Override    public void onStart(Intent intent, int startid) {        Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();        Log.i(TAG, "onStart");        player.start();    }}

layout檔案夾中是main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:gravity="center"><TextView    android:layout_width="fill_parent"    android:layout_height="wrap_content" android:text="@string/services_demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/><Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="@string/start"></Button><Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/stop" android:id="@+id/buttonStop"></Button></LinearLayout>

values 檔案夾中是strings.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="start">Start</string>    <string name="stop">Stop</string>    <string name="services_demo">Service Demo</string></resources>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.