gpt4 book ai didi

将 UI 从 BroadcastReceiver 更新到特定 Activity 的 Android 最佳实践

转载 作者:IT老高 更新时间:2023-10-28 22:17:20 26 4
gpt4 key购买 nike

当我有一个广播接收器说 android.intent.action.MEDIA_BUTTON 并且我想在不创建新 Activity 的情况下更新当前 Activity 的 UI 时,有什么好的做法吗?

我知道的(可能不正确)

1)我可以把BroadcastReceiver和activity放在同一个类中,在某个activity之后调用updateUI函数

2) 创建一个 ContentObserver?

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

4)在与activity位于同一类的broadcastReceiver上创建一个自定义过滤器,并使用context.sendBroadcast(msg of custom filter)并在自定义过滤器调用updateUI(同一个但更通用?)

最终流程是来自 BroadcastReceiver 并最终更新 UI 而不更新 Activity (除非 Activity 已死?)

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

最佳答案

提供此功能的最简单方法是将广播接收器放入您的 Activity 并使用 registerReceiverunregisterreceiver 绑定(bind)/取消绑定(bind)它:

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

根据您希望接收的 Intent ,您可能需要向 AndroidManifest.xml 文件添加适当的权限。

关于将 UI 从 BroadcastReceiver 更新到特定 Activity 的 Android 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3275042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com