1. 程式人生 > >Android——活動與服務之間的通訊與服務的生命週期

Android——活動與服務之間的通訊與服務的生命週期

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        downloadBinder = (MyService.DownloadBinder) service;
        downloadBinder.startDownload();
        downloadBinder.getProgress();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startService = findViewById(R.id.start_service);
        Button stopService = findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);

        Button bindService = findViewById(R.id.bind_service);
        Button unbindService = findViewById(R.id.Unbind_Service);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_service:
                Intent startIntent = new Intent(this,MyService.class);
                startService(startIntent);//啟動服務
                break;
            case R.id.stop_service:
                Intent stopIntent = new Intent(this,MyService.class);
                startService(stopIntent);
                break;
            case R.id.bind_service://繫結服務
                Intent bindIntent = new Intent(this,MyService.class);
                bindService(bindIntent,connection,BIND_AUTO_CREATE);
                break;
            case R.id.Unbind_Service://取消服務繫結
                unbindService(connection);
                break;
                default:break;
        }
    }
}

一旦專案在任意位置呼叫了Context中的startService方法,相應的伺服器就會啟動,並回調onStartCommand方法,如果這個服務之前還沒有建立過。onCreate會優先於onStartCommand方法執行,服務啟動了會一直保持執行狀態,直到stopService或stopSelf方法被呼叫,每當呼叫一次startService,onStartCommand就會執行一次,但其實每個服務只有一個例項,所以無論呼叫多少次startService方法,只需要呼叫一次stopService或者stopSelf方法服務就會停止了。

可以呼叫Context中的bindService來獲取一個服務的持久連線,這時就會回撥服務中的onBind,呼叫房可以獲得到onBind方法裡返回的IBinder物件的例項,這樣就能自由地和服務進行通訊了,只要呼叫方和服務之間的連線沒有斷開,服務就會制止保持執行狀態

start之後使用stop會回撥用onDestory

bind之後使用unbind會呼叫onDestory

start和bind同時使用需要同時使用stop和unbind才會呼叫onDestory