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

猜你喜欢

转载自blog.csdn.net/castanea/article/details/80490670
今日推荐