2016-03-05 130 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繼續運行。

相關問題