2013-05-29 63 views
0

我在應用程序中有一個本地服務,它在asynctask中執行一些網絡操作。android本地服務問題

在我的應用程序有兩個活動,活動A和B.活動

我服務的生命週期和活動,是這樣的。

In activity A: 
1)stop service(in oncreate) 

In activity B: 
1)start service(in oncreate) 
2)bindservice(in oncreate) 
3)unbind service(in on destroy) 

In service: 
1)start download in async task(in oncreate) 
2)stop async task(in ondestroy) 

但是服務仍在running.is有什麼iam失蹤? 感謝

FIX: 
i need to stop the async task before i call stopService. As the service is busy with asyn task, it will ignore my my stop requests. 
1)send a msg to service in intent extra, to stop async task. 
2)then call stop service 

回答

0

所有bindService()調用後,服務將關閉有其相應的unbindService()調用。如果沒有綁定的客戶端,那麼當且僅當有人在服務上調用startService()時,服務還需要stopService()。
因此,您需要調用stopService()來停止您在活動B onDestroy中的活動B 1)start service(in oncreate)中開始的服務。
閱讀完您的評論後,以下內容可爲您完成工作。無需綁定服務。

public class DownloadService extends Service { 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     new DownloadTask().execute(); 

     return START_STICKY; 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 

     return null; 
    } 

    @Override 
    public void onDestroy() { 
     Log.i(TAG, "Service destroyed!"); 
    } 


    public class DownloadTask extends AsyncTask<String, Void, String>{ 

     @Override 
     protected String doInBackground(String... params) { 
      // download here 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 

      } 
    } 

} 

從這裏stopService在活動A和startActivity在活動B.

+0

我不想停止活動B中的服務,我想阻止它在一個如果用戶再次--thx啓動應用程序 –

+0

在這種情況下,您需要解除活動A中的服務。 –

+0

我發現該缺陷,請參閱更新後的帖子。非常感謝你的幫助。 –