关于将UI从BroadcastReceiver更新为特定活动的Android最佳实践

当我有一个broadcastReceiver说android.intent.action.MEDIA_BUTTON并且我想在不创建新活动的情况下更新当前活动的UI时,这个有什么好的做法吗?

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

1)我可以将BroadcastReceiver放在与活动相同的类中,并在某些活动后调用updateUI函数

2)创建一个ContentObserver?

3)与活动创建的服务进行通信,使用aidl。 (如果从活动中注册,我不知道如何获得当前服务)

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

最后一个流程是来自BroadcastReceiver并最终更新UI而不更新活动(除非活动已经死了?)

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

Solutions Collecting From Web of "关于将UI从BroadcastReceiver更新为特定活动的Android最佳实践"

提供此function的最简单方法是将广播接收器放入Activity中,并使用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"); } }