我可以在android中完全重新启动服务吗?
问题描述:
我正在通过服务和异步任务内运行后台任务。首先,它从数据库获取所有数据,并在用户更改某些选项时开始运行,我销毁并再次启动服务以处理新数据,但不幸的是,服务从停止的位置运行。所以我想开始全新的服务。我试过START_NOT_STICKY
但没用。我可以在android中完全重新启动服务吗?
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);
}
}
}
}
我的活动在这里的代码是如何重新启动服务
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);
}
}
答
我想你没有正确停止你的服务,你的异步任务不断在后台运行。你需要取消你的asynctask以及破坏你的服务。
答
服务是在后台运行,而无需与用户交互 它的工作原理,即使应用程序被破坏执行 长时间运行操作的组件。
AsyncTask支持正确和方便地使用UI线程。该类 允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。
,所以你不能阻止你的服务因为你的AsyncTask继续运行。
谢谢你的哥们。我不知道我是如何错过它的。 – Thamaraiselvam
欢迎兄弟:)有时它也发生在我身上 –