2013-05-29 65 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

我发现该缺陷,请参阅更新后的帖子。非常感谢你的帮助。 –