天天看點

Android 四大元件--service的使用與生命周期

1. 什麼是服務(service)

官方給出的解釋:

A Service is an application component that can perform long-running operations in the background, and it doesn’t provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application

Service 是一個可以在背景執行長時間運作操作而不提供使用者界面的應用元件。服務可由其他應用元件啟動,而且即使使用者切換到其他應用,服務仍将在背景繼續運作。要注意的是服務預設在應用程式的主線程中運作,如果要在服務中進行耗時操作,建議使用 IntentService。

2. 基本使用

啟動 service 的方法有兩種,一種是 startService(),一種是 bindService()。不同的啟動方式有不同的生命周期。

Android 四大元件--service的使用與生命周期

2.1 startService()

這種方式比較簡單,在 AndroidManifest.xml 檔案中注冊後就可啟動

// 啟動服務
startService(Intent(this, ComponentService::class.java))

// 結束服務
stopService(Intent(this, ComponentService::class.java))
           

開啟服務時,Service 會調用 onCreate() 方法,然後在調用 onStartCommand() ,多次調用 startService() 啟動統一服務,該服務隻會調用一次 onCreate() 方法,之後再調用直接執行 onStartCommand() ,如果想結束服務,調用 stopService() 或者在 Service 中調用 stopSelf() 即可。如果不調用,該服務會一直存在,直到應用結束,或者記憶體不足被回收。

2.2 bindService()

綁定服務

val conn = object:ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {
        //隻有當我們自己寫的MyService的onBind方法傳回值不為null時,才會被調用
            Log.i(TAG, "onServiceDisconnected")
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        //這個方法隻有出現異常時才會調用,伺服器正常退出不會調用。
           // (service as ComponentService.MyBinder).print()
            Log.i(TAG, "onServiceConnected")
        }
    }
  // 綁定服務
bindService(Intent(this,ComponentService::class.java),conn, Context.BIND_AUTO_CREATE)
           

解綁服務

unbindService(conn)
           

被綁定了的服務,一定要解綁,如果在 activity 中綁定,在退出 activity 時沒有解綁,會造成記憶體洩漏。

E/ActivityThread: Activity lxy.com.kotlinandroid.component.Component2Activity has leaked ServiceConnection lxy.com.kotlinandroid.component.Component2Activity$conn$1@62f65fb that was originally bound here
                  android.app.ServiceConnectionLeaked: Activity lxy.com.kotlinandroid.component.Component2Activity has leaked ServiceConnection lxy.com.kotlinandroid.component.C[email protected] that was originally bound here
           

同時,unbindService() 隻能調用一次,多次調用會報錯。

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: lxy.com.kotlinandroid, PID: 16281
                  java.lang.IllegalArgumentException: Service not registered: lx[email protected]
           

總結一下,通過 bindService() 啟動的服務,生命周期為 onStart() => onBind() => onUnbind() —> onDestroy()。需要注意的是關閉服務需要 stopService 和 unbindService 都被調用,沒有先後順序的影響,隻調用其中一個方法,onDestory() 都不會執行,服務也不會被關閉。

同時要注意的是 service 運作并不是單獨的一個程序或線程,它是運作在主線程中的,是以盡可能的不在service 中進行耗時操作,否則會引起 ANR (前台服務20s,背景服務200s)。如果實在要在 service 中進行耗時操作的話,可以使用 IntentService 。

IntentService

IntentService 繼承 Service,與至不同的是 IntentService 在建立之後會另起一個線程,耗時操作可以運作在該線程中。其實主要是繼承一個方法:

override fun onHandleIntent(intent: Intent?) {
		// 執行耗時操作
    }
           

那麼為什麼 IntentService 不用擔心 ANR 問題呢?這個可以去源碼裡面找答案。

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * <p>If enabled is true,
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
     * {@link #onHandleIntent(Intent)} returns, the process will be restarted
     * and the intent redelivered.  If multiple Intents have been sent, only
     * the most recent one is guaranteed to be redelivered.
     *
     * <p>If enabled is false (the default),
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
     * dies along with it.
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

    /**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null.
     * @see android.app.Service#onBind
     */
    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * This method is invoked on the worker thread with a request to process.
     * Only one Intent is processed at a time, but the processing happens on a
     * worker thread that runs independently from other application logic.
     * So, if this code takes a long time, it will hold up other requests to
     * the same IntentService, but it will not hold up anything else.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {@link #stopSelf}.
     *
     * @param intent The value passed to {@link
     *               android.content.Context#startService(Intent)}.
     *               This may be null if the service is being restarted after
     *               its process has gone away; see
     *               {@link android.app.Service#onStartCommand}
     *               for details.
     */
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);
}
           

通過源碼可以看出,在 onCreate() 方法中開啟了一個線程,同時初始化了一個 handler ,在 onStartCommand() 方法中調用 onStart() 使用 handler 發送一個無延遲的消息,然後調用了我們實作的 onHandleIntent() 方法,執行耗時操作,是以不用擔心 ANR。

注意,IntentService 在處理完所有啟動請求後停止服務,是以不必調用 stopSelf()。