在android中显示来自短信接收器的对话框

时间:2013-07-25 08:43:02

标签: android dialog

我有一个smsReceiver,每当我得到一个sms我想要触发一个poppup。我的smsreceiver方法会在sms到来时被触发。然后我尝试调用一个对话框

@overide //of smsreciver class
public void onReceive(Context context, Intent intent){
  showNotificattion(context)
}

private void showNotificattion(Context context){
        Log.d("sms","showing notification now 2");

         // Create out AlterDialog
          Builder builder = new AlertDialog.Builder(context); 
          //even tried context.getApplicationcontext()
          builder.setMessage("This will end the activity");
          builder.setCancelable(true);
          builder.setPositiveButton("I agree", new OkOnClickListener());
          builder.setNegativeButton("No, no", new CancelOnClickListener());
          AlertDialog dialog = builder.create();
          dialog.show();
}

但是每当有短信出现时我都会跟着

07-25 14:02:04.235: E/AndroidRuntime(17935): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
07-25 14:02:04.235: E/AndroidRuntime(17935):    at android.view.ViewRoot.setView(ViewRoot.java:566)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:179)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at android.app.Dialog.show(Dialog.java:265)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at com.example.xsms.SmsReceiver.showNotificattion(SmsReceiver.java:92)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at com.example.xsms.SmsReceiver.doTask(SmsReceiver.java:73)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at com.example.xsms.SmsReceiver.onReceive(SmsReceiver.java:44)
07-25 14:02:04.235: E/AndroidRuntime(17935):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2103)
07-25 14:02:04.235: E/AndroidRuntime(17935):    ... 10 more

如何解决这个问题? 我想将我的应用程序作为后台服务运行,对话框应该是可见的

1 个答案:

答案 0 :(得分:2)

您使用了错误的Context

BroadcastReceiverService无法启动对话框。

您应该使用对话框主题制作Activity并使用startActivity()

启动它
<activity android:theme="@android:style/Theme.Dialog" />