Android的最佳实践更新的BroadcastReceiver从用户界面到一定的活动 [英] Android Best Practice on Updating the UI from BroadcastReceiver to a certain activity

查看:123
本文介绍了Android的最佳实践更新的BroadcastReceiver从用户界面到一定的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个BroadcastReceiver说android.intent.action.MEDIA_BUTTON,我想更新当前活动的用户界面,而无需创建一个新的活动,有没有在这一个有什么好的做法?

When i have a broadcastReceiver say android.intent.action.MEDIA_BUTTON and i want to update the current activity's UI without creating a new activity, is there any good practice on this one?

我所知道的(可能不正确)

What i know (might not be correct)

1)我可以一定的活动后把的BroadcastReceiver在同一类的活动,并调用函数的updateUI

1) I can put the BroadcastReceiver in the same class as the activity and call the updateUI function after certain activity

2)创建ContentObserver?

2) Create a ContentObserver?

3)沟通,由活动创建一个服务,使用AIDL。 (我不知道如何获得当前的服务,如果它从活动注册)

3) Communicate to a service created by the activity, use aidl. (I dont know how to get the current service if its registered from an activity)

4)创建于位于同一类作为活动的BroadcastReceiver自定义过滤器,并使用context.sendBroadcast(自定义过滤器的MSG)和自定义过滤器调用的updateUI(同为一个更通用的?)

4) Create a custom filter on the broadcastReceiver located on the same class as the activity, and use context.sendBroadcast(msg of custom filter) and in the custom filter call updateUI (same as one but more generic?)

最后一个流程是将来自一个BroadcastReceiver,并最终更新UI没有更新活动(除非该活动是死了吗?)

The final flow is it would come from a BroadcastReceiver and ends up updating the UI without renewing the activity (unless the activity is dead?)

请提供链接/来源$ C ​​$ c。关于你的,你是如何解决这类问题。非常感谢提前:)

Kindly provide links/source code on your how you tackle this kind of problem. Thanks a lot in advance :)

推荐答案

要提供此功能的最简单方法是将广播接收器在你的活动和绑定/使用解除绑定的 registerReceiver unregisterreceiver 的:

The easiest way to provide this functionality is to put the broadcast receiver in you Activity and bind / unbind it using registerReceiver and unregisterreceiver:

public class MyActivity extends Activity {
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyActivity.this.receivedBroadcast(intent);
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        IntentFilter iff = new IntentFilter();
        iff.addAction("android.intent.action.MEDIA_BUTTON");
        // Put whatever message you want to receive as the action
        this.registerReceiver(this.mBroadcastReceiver,iff);
    }
    @Override
    public void onPause() {
        super.onPause();
        this.unregisterReceiver(this.mBroadcastReceiver);
    }
    private void receivedBroadcast(Intent i) {
        // Put your receive handling code here
    }
}

根据您希望收到的意图,可能需要适当的权限添加到您的的Andr​​oidManifest.xml 的文件。

这篇关于Android的最佳实践更新的BroadcastReceiver从用户界面到一定的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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