android代码关闭程序后服务还在运行怎么办
如果想要停止服务,可以在Activity销毁时调用stopService()方法停止服务。例如,在Activity的onDestroy()方法中调用stopService()方法:
@Override
protected void onDestroy() {
super.onDestroy();
// 停止服务
stopService(new Intent(this, MyService.class));
}
另外,如果服务在后台运行,可以通过设置服务的优先级为START_STICKY,使得服务在被系统回收后可以自动重启。可以在服务的onStartCommand()方法中返回START_STICKY:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// ...
return START_STICKY;
}
原文地址: https://www.cveoy.top/t/topic/bsmS 著作权归作者所有。请勿转载和采集!