Subscribing or binding to an existing Intent service

て烟熏妆下的殇ゞ 提交于 2019-12-04 03:26:36

问题


I have an app that has an initial activty that list some files within a list view. When an item is clicked within the list it takes you to a detail activity of that specific file.

In the detail view I have a button called download, when you click on download it starts a IntentService which sets off the file to be downloaded as such:

downloadButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(AppDetailsActivity.this, AppDownloadService.class);
        intent.putExtra(Consts.APP_DOWNLOAD_RECEIVER_KEY, new DownloadReceiver(new Handler()));
        startService(intent);
    }
});

the DownloadReceiver class is used to update a progress bar within the the download file's detailed activity.

Now what I want to do...

If the user is currently downloading the file from the detail activity, and then goes back to the previous activity, I want the activity to somehow subscribe/bind to the same IntentService and retrieve the results so that it can show a progress bar within the list item of the file that is downloading.

  1. Is this possible using an IntentService?
  2. Is IntentService the right thing?
  3. Are there any examples (as I have not found anything that show's me how to do this)?

回答1:


For a download you sure can use an IntentService. It runs on a different thread. Also, keep in mind that calling startService() several times for that IntentService it will create a queue and will handle one intent at a time.

To show the progress on an Activity I don't belive broadcasts are the right thing. Although it is highly likely they are process in order, the framework or Android itself won't guarantee an order upon delivery. This means that you can get the broadcast for 50% and then the broadcast for 40%. For this I recommend that you take a look on this example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

It can look a little bit more complicated but you'll have a 2 way communication that you can rely on.




回答2:


I managed to find a solution. It turns out that I have to use a broadcast intent to publish the progress in my service; And use BroadcastReceiver in my activities to retrieve the results.

The link below shows an example of sending and retrieving results from services via broadcasts.

http://mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/



来源:https://stackoverflow.com/questions/13343627/subscribing-or-binding-to-an-existing-intent-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!