0

i have a local service in application, which does some network operation in the asynctask.

In my application there are two activities activity A and activity B.

the life cycle of my service is and activities is like this.

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)

But the service is keep on running.is there something iam missing? Thanks

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 
4

1 回答 1

0

在所有 bindService() 调用都有相应的 unbindService() 调用后,服务将关闭。如果没有绑定的客户端,那么当且仅当有人在服务上调用 startService() 时,服务也需要 stopService()。
因此,您需要在 Activity B 中调用 stopService() 来停止您在 Activity B 中启动的1)start service(in oncreate)服务onDestroy
阅读您的评论后,以下内容可以为您完成工作。无需绑定服务。

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) {

            }
    }

}

从这里 Activity A 中的 stopService 和 Activity B 中的 startActivity 开始。

于 2013-05-29T05:52:11.993 回答