How to use an intent to update an activity?

前端 未结 2 989
臣服心动
臣服心动 2020-12-28 08:12

I have a service that is downloading a file. When the download is done, I would like to update my \"Downloaded files\" list in my Activity, but only if the

相关标签:
2条回答
  • 2020-12-28 09:05

    The good way to do this is to bind your "Downloaded files" activity to the service. When you bind the service, in the function onServiceConnected, register a Binder callback. Then, whenever you have new data available, service just calls that callback. If the activity is not running, the callback list at the service side will be empty, so it will not inform your activity.

    For an example of this approach, take a look at RemoteService.java in Android SDK:

    samples\ApiDemos\src\com\example\android\apis\app\

    0 讨论(0)
  • 2020-12-28 09:17

    You can create new BroadcastReceiver instance and do something along these lines on your Activity's onResume() method:

    registerReceiver(myReceiver, new IntentFilter(DownloadService.ACTION_FILE_DOWNLOADED));
    

    After that, override myReceiver's onReceive() method to call a function that updates the component you want:

    @Override 
    public void onReceive(Context context, Intent intent) {
    ...
        updateViewWithData(service.getNewFileData());
    ...
    }
    

    On your Activity's onPause() method, just unregister the receiver:

    unregisterReceiver(myReceiver);
    

    I hope that this would help you, feel free to ask if there is something unclear.

    0 讨论(0)
提交回复
热议问题