Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android教程之service使用方法示例詳解

android教程之service使用方法示例詳解

編輯:關於Android編程

Service的生命周期 (適用於2.1及以上)

1. 被startService的
無論是否有任何活動綁定到該Service,都在後台運行。onCreate(若需要) -> onStart(int id, Bundle args).  多次startService,則onStart調用多次,但不會創建多個Service實例,只需要一次stop。該Service一直後台運行,直到stopService或者自己的stopSelf()或者資源不足由平台結束。

2. 被bindService的
調用bindService綁定,連接建立服務一直運行。未被startService只是BindService,則onCreate()執行,onStart(int,Bundle)不被調用;這種情況下綁定被解除,平台就可以清除該Service(連接銷毀後,會導致解除,解除後就會銷毀)。

3. 被啟動又被綁定
類似startService的生命周期,onCreate onStart都會調用。

4. 停止服務時
stopService時顯式onDestroy()。或不再有綁定(沒有啟動時)時隱式調用。有bind情況下stopService()不起作用。

以下是一個簡單的實現例子,某些部分需要配合logcat觀察。
AcMain.java

復制代碼 代碼如下:
package jtapp.myservicesamples;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AcMain extends Activity implements OnClickListener {
        private static final String TAG = "AcMain";
        private Button btnStart;
        private Button btnStop;
        private Button btnBind;
        private Button btnExit;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findView();
    }
        private void findView() {
                btnStart = (Button) findViewById(R.id.Start);
        btnStop = (Button) findViewById(R.id.Stop);
        btnBind = (Button) findViewById(R.id.Bind);
        btnExit = (Button) findViewById(R.id.Exit);

        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnBind.setOnClickListener(this);
        btnExit.setOnClickListener(this);
        }
        @Override
        public void onClick(View v) {
                Intent intent = new Intent("jtapp.myservicesamples.myservice");
                switch(v.getId()) {
                case R.id.Start:
                        startService(intent);
                        Toast.makeText(this,
                                        "myservice running " + MyService.msec/1000.0 + "s.",
                                        Toast.LENGTH_LONG).show();
                        break;
                case R.id.Stop:
                        stopService(intent);
                        Toast.makeText(this,
                                        "myservice running " + MyService.msec/1000.0 + "s.",
                                        Toast.LENGTH_LONG).show();
                        break;
                case R.id.Bind:
                        bindService(intent, sc, Context.BIND_AUTO_CREATE);
                        break;
                case R.id.Exit:
                        this.finish();
                        break;
                }
        }

        private MyService serviceBinder;

        private ServiceConnection sc = new ServiceConnection() {
                @Override
                public void onServiceDisconnected(ComponentName name) {
                        Log.d(TAG, "in onServiceDisconnected");
                        serviceBinder = null;
                }
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                        Log.d(TAG, "in onServiceConnected");
                        serviceBinder = ((MyService.MyBinder)service).getService();
                }
        };
        @Override
        protected void onDestroy() {
                //this.unbindService(sc);
                //this.stopService(
                //                new Intent("jtapp.myservicesamples.myservice"));
                super.onDestroy();
        }
}

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">
        <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:text="@string/hello" />
        <Button android:text="Start MyService" android:id="@+id/Start"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:text="Stop MyService" android:id="@+id/Stop"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:text="Bind MyService" android:id="@+id/Bind"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:text="Exit AcMain" android:id="@+id/Exit"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>

MyService.java

復制代碼 代碼如下:
package jtapp.myservicesamples;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
        private static final String TAG = "MyService";
        public static long msec = 0;
        private boolean bThreadRunning = true;

       
        private final IBinder binder = new MyBinder();
        public class MyBinder extends Binder {
                MyService getService() {
                        return MyService.this;
                }
        }
        @Override
        public IBinder onBind(Intent intent) {
                return binder;
        }
        @Override
        public void onCreate() {
                new Thread(new Runnable(){
                        @Override
                        public void run() {
                                while (bThreadRunning) {
                                        try {
                                                Thread.sleep(100);
                                        } catch (InterruptedException e) {
                                        }
                                        Log.i(TAG, "myservice running " + (msec+=100) + "ms.");
                                }
                        }
                }).start();
        }
        @Override
        public void onDestroy() {
                bThreadRunning = false;
                super.onDestroy(); // 可以不用
        }
}

AnndroidManifest.xml

復制代碼 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="jtapp.myservicesamples" android:versionCode="1"
        android:versionName="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name"
                android:debuggable="true">
                <activity android:name=".AcMain" 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:name="MyService">
                        <intent-filter>
                                <action android:name="jtapp.myservicesamples.myservice"></action>
                        </intent-filter>
                </service>
        </application>
</manifest>

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved