天天看點

【Android】startService和bindService混合使用總結

先自定義一個service:

public class MyService extends Service {
    private Service startService;
    private Service bindService;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("TestService", "onBind...");
        bindService = this;
        if (bindService == startService) {
            Log.i("TestService", "bindService == startService");
        } else {
            Log.i("TestService", "bindService != startService");
        }
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("TestService", "onUnbind...");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("TestService", "onCreate...");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("TestService", "onStartCommand...");
        startService = this;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("TestService", "onDestroy...");
    }
}
           

1、單獨使用startService & stopService

(1)第一次調用startService會執行onCreate、onStartCommand。

(2)之後再多次調用startService隻執行onStartCommand,不再執行onCreate。

(3)調用stopService會執行onDestroy。

2、單獨使用bindService & unbindService

(1)第一次調用bindService會執行onCreate、onBind。

(2)之後再多次調用bindService不會再執行onCreate和onBind。

(3)調用unbindService會執行onUnbind、onDestroy。

3、startService與bindService混合使用

使用場景:在activity中要得到service對象進而能調用對象的方法,但同時又不希望activity finish的時候service也被destory了,startService和bindService混合使用就派上用場了。

(1)先調用startService,再調用bindService,生命周期如下:

startService(new Intent(this, MyService.class));

bindService(new Intent(this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);

onCreate-onStartCommand-onBind

(2)先調用bindService,再調用startService,生命周期如下:

bindService(new Intent(this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);

startService(new Intent(this, MyService.class));

onCreate-onBind-onStartCommand

(3)先調用startService又調用了bindService,他們對應的是同一個service對象嗎?

答案是的。

論點1:service輸出“bindService == startService”。

論點2:如果不是同一個service,應該會執行兩次onCreate。