如何在一个BroadcastReceiver更新UI [英] How to update UI in a BroadcastReceiver
问题描述
我创造的,我注册的广播接收器在我的主类的应用程序(主要活动
),每当我收到东西在我的的BroadcastReceiver
我想更新用户界面,例如我想显示一个警告框,或设置一些文本视图我的 MainActivity
。我收到我的接收器所有的值,但无法对其进行设置,可以有人帮助我,让我可以更新我的UI中的的BroadcastReceiver
。
I created an application in which I registered a broadcast receiver within my main class(Main Activity
) and whenever I receive something in my BroadcastReceiver
I want to update UI for e.g. I want to show an alert box or set some text view of my MainActivity
. I receive all the values in my receiver but unable to set them, can somebody help me so that I can update my UI in the BroadcastReceiver
.
我的BroadcastReceiver类是内部类MainActivity像这样的: -
My BroadcastReceiver class is inner class of MainActivity like this :-
public class MainActivity extends Activity {
..........
public static class NissanTabBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences shrd = context.getSharedPreferences("NissanGallery", context.MODE_WORLD_READABLE);
type = shrd.getString("type", "null");
badges = shrd.getString("badge_count", "null");
//badge_tips_text.setText(badges);
/*Editor edit = shrd.edit();
edit.remove("type");*/
Toast.makeText(context, "" + type + "\n" + badge_tips_text.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
任何帮助将AP preciable
Any help will be appreciable
感谢
推荐答案
我建议你使用一个处理器。
I suggest you use a Handler.
- 在初始化处理程序中的活动,例如:
处理程序=新的处理程序()
- 提供处理程序的的BroadcastReceiver在构造函数中,以同样的方式,像我一样的NissanTabBroadcast上述 在
- 使用
后()
方法提交了Runnable的更新用户界面
的onReceive()
方法的处理程序实例- Initialize a Handler in the Activity, example:
handler = new Handler()
- Provide the handler to the BroadcastReceiver in the constructor, in the same way as I did for NissanTabBroadcast above
- Use
post()
method of your Handler instance in theonReceive()
method to submit the Runnable that updates the UI
这是我能想象最干净的解决方案。
This is the cleanest solution I can imagine.
public class MainActivity extends Activity {
private MyReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new MyReceiver(new Handler()); // Create the receiver
registerReceiver(receiver, new IntentFilter("some.action")); // Register receiver
sendBroadcast(new Intent("some.action")); // Send an example Intent
}
public static class MyReceiver extends BroadcastReceiver {
private final Handler handler; // Handler used to execute code on the UI thread
public MyReceiver(Handler handler) {
this.handler = handler;
}
@Override
public void onReceive(final Context context, Intent intent) {
// Post the UI updating code to our Handler
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Toast from broadcast receiver", Toast.LENGTH_SHORT).show();
}
});
}
}
}
这篇关于如何在一个BroadcastReceiver更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!