如何使用意图来更新活动? [英] How to use an intent to update an activity?

查看:119
本文介绍了如何使用意图来更新活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下载文件的服务。当下载完成后,我想更新我的活动,但前提是活动运行。我不想让活动来启动,如果它尚未运行。

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 Activity is running. I do not want the Activity to start if it's not already running.

我希望我可以通过一个新的做意图有一些特殊的标志。

I was hoping I could do this by making a new Intent with some special flag.

任何人有任何想法我如何能做到这一点?一个小小的code例如可能?

Anyone have any idea how I can achieve this? A tiny code example maybe?

推荐答案

您可以创建新的BroadcastReceiver实例,并做一些事情沿着你的Activity的onResume这些行()方法:

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

在此之后,覆盖myReceiver的的onReceive()方法来调用一个函数,更新所需的组件:

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());
...
}

在你活动的的onPause()方法,只是注销接收器:

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.

这篇关于如何使用意图来更新活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆