最佳实践Android更新从BroadcastReceiver的用户界面到某个活动

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

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

1)我可以把BroadcastReceiver放在与activity相同的类中,并在一定的activity后调用updateUI函数

2)创build一个ContentObserver?

3)通过活动创build的服务,使用aidl。 (如果从活动注册,我不知道如何获得当前的服务)

4)在与活动位于同一类的broadcastReceiver上创build一个自定义filter,并使用context.sendBroadcast(自定义filter的消息)和自定义filter调用updateUI(相同,但更通用?)

最后的stream程是来自BroadcastReceiver,并最终更新UI而不更新活动(除非活动已经死亡?)

请提供关于如何解决这类问题的链接/源代码。 非常感谢:)

Solutions Collecting From Web of "最佳实践Android更新从BroadcastReceiver的用户界面到某个活动"

提供此function的最简单方法是将广播接收器放入您的活动中,并使用registerReceiverunregisterreceiver绑定/解除绑定:

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 } } 

根据您希望收到的意图,您可能需要将相应的权限添加到您的AndroidManifest.xml文件。

从LocalBroadcastManager接收数据后,我最近必须做的改变button的文本是将值存储在一个专用字段,然后在我的onResume()方法做UI的东西。

 public class myClass extends Activity { private String myString; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // register to receive data LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("myAction")); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // get the extra data included in the intent myString = intent.getStringExtra("myString"); } }; @Override public void onResume() { super.onResume(); System.out.println("onResume"); // do something to the UI myButton.setText(myString != null ? myString : "Default"); } }