android – 如何在BroadcastReceiver中更新UI

我创建了一个应用程序,其中我在我的主类(主要活动)中注册了一个广播接收器,每当我收到我的BroadcastReceiver中的某些东西,我想更新UI,例如我想显示一个提醒框或设置我的MainActivity的一些文本视图。我收到接收器中的所有值,但无法设置它们,可以帮助我,以便我可以在BroadcastReceiver中更新我的用户界面。

我的BroadcastReceiver类是MainActivity的内部类,如下所示:

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();
        }
    }
}

任何帮助将是可观的

谢谢

我建议你使用一个处理程序。

>在Activity中初始化处理程序,例如:handler = new Handler()
>在构造函数中向BroadcastReceiver提供处理程序,方式与上面的NissanTabBroadcast相同
>在onReceive()方法中使用你的Handler实例的post()方法来提交更新UI的Runnable

这是我能想到的最干净的解决方案。

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();
                }
            });
        }
    }
}
http://stackoverflow.com/questions/14643385/how-to-update-ui-in-a-broadcastreceiver

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:android – 如何在BroadcastReceiver中更新UI