来自c2dm监听器事件的触发警报框

时间:2012-01-07 19:07:36

标签: android

每当侦听器收到消息时,我都希望将进度和警报对话框添加到活动上下文中。使用此代码:

public class C2DMMessageReceiver extends BroadcastReceiver {
        @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    Log.w("C2DM", "Message Receiver called");
                    if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
                        Log.w("C2DM", "Received message");
                        final String payload = intent.getStringExtra("payload");
                        Log.d("C2DM", "dmControl: payload = " + payload);

                        // Message handling
                        if(payload.equals("DataUpdate")) {
                            progressDialog = ProgressDialog.show(context, "Please wait...", "Synchronizing data ...", true);
                syncData(context);
                progressDialog.dismiss();
                AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
                alertbox.setMessage("Data was updated");
                alertbox.create();
                alertbox.show();
                        }
                    }
                }
    }

收到消息时收到以下错误:

01-07 08:44:38.190: E/AndroidRuntime(750): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

试图弄清楚处理这个问题的最佳方法是,我是否需要在单例中缓存活动上下文,然后从侦听器访问所述单例?或者,还有更好的方法?

由于

1 个答案:

答案 0 :(得分:1)

无法从Dialog创建/显示BroadcastReceiver。请参阅此SO问题的答案android-broadcast-receiver-showing-a-dialog

另外要仔细考虑这样做 - 正如在这个问题的答案中所提到的那样,你真的想在他们正在做其他事情的时候通过强制弹出他们来惹恼用户吗?

处理C2DM消息的首选方法通常是静默和无形地处理,或者只是创建一个用户可以在以后采取行动的Notification