2016-03-05 79 views
1

我正在通过服务和异步任务内运行后台任务。首先,它从数据库获取所有数据,并在用户更改某些选项时开始运行,我销毁并再次启动服务以处理新数据,但不幸的是,服务从停止的位置运行。所以我想开始全新的服务。我试过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); 
     } 
} 

回答

1

我想你没有正确停止你的服务,你的异步任务不断在后台运行。你需要取消你的asynctask以及破坏你的服务。

+0

谢谢你的哥们。我不知道我是如何错过它的。 – Thamaraiselvam

+1

欢迎兄弟:)有时它也发生在我身上 –

1

你不停止服务property.I认为你可以注册一个广播AndroidManifest.xml重新启动服务或销毁服务。

+0

谢谢我没有停止异步,这是一个问题 – Thamaraiselvam

1

服务是在后台运行,而无需与用户交互 它的工作原理,即使应用程序被破坏执行 长时间运行操作的组件。

AsyncTask支持正确和方便地使用UI线程。该类 允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

,所以你不能阻止你的服务因为你的AsyncTask继续运行。

相关问题