相关文章:
Android 知识点总结(目录) https://blog.csdn.net/a136447572/article/details/81027701
Android 知识点总结 (六)Service的生命周期,两种启动方法
两种启动service的方式:startService和bindService
直接开启startService,使用stopService关闭。
onCreate()
onStartCommand()
stopService()
onDestroy()
开启bindService,使用unbindService解绑关闭。
onCreate()
onBind()
onUnbind()
onDestroy()
start和stop只能开启和关闭,无法操作service。bind和unbind可以操作service。
start开启的service,调用者退出后service仍然存在。bind开启的service,调用者退出后,随着调用者销毁。
/** startService 启动服务 */
Intent intent = new Intent(MainActivity.this,
CountService.class);
startService(intent);
CountService countService;
private ServiceConnection conn = new ServiceConnection() {
/** 获取服务对象时的操作 */
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
countService = ((CountService.ServiceBinder) service).getService();
}
/** 无法获取到服务对象时的操作 */
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
countService = null;
}
};
/** bindService 启动服务 */
Intent intent = new Intent(UseBrider.this, CountService.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);