我正在通过其中的服务和异步任务运行后台任务。首先,它从数据库中获取所有数据并在用户更改某些选项时开始运行我销毁并再次启动服务以处理新数据但不幸的是服务从它停止的地方运行。所以我想开始全新的服务。我试过 START_NOT_STICKY
但没用。
public class MyService extends Service {
public void onCreate(){
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
process.execute();
return START_NOT_STICKY;
}
public void onDestroy() {
stopSelf();
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
class ProcessImageAsync extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
// here im getting content from db and processing .
if (isCancelled()) {
System.exit(0);
}
}
}
}
这里的 Activity 代码是我如何重启服务
public void startServiceFucntion(int type){
if(isMyServiceRunning(MyService.class)){
if (type == 1){
Intent serviceIntent = new Intent(this, MyService.class);
stopService(serviceIntent);
startServiceFucntion(0);
}
} else {
Intent serviceIntent = new Intent(this, MyService.class);
if(serviceReceiver == null){
registerReceiver(serviceReceiver, intentSFilter);
}
startService(serviceIntent);
}
}
最佳答案
我认为您没有正确停止服务,您的异步任务继续在后台运行。您还需要在销毁服务时取消异步任务。
关于android - 我可以在 android 中完全重新启动服务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810347/