【发布时间】:2011-06-18 03:49:26
【问题描述】:
BroadcastReceiver 中的AlertDialog?可以做到吗?我正在开发一个应用程序,如果我收到短信,它会弹出一个对话框。我正在尝试在 BroadcaseReceiver 中对此进行编码。但是我不能使用这行代码AlertDialog.Builder builder = new AlertDialog.Builder(this);。有人可以帮我一个提示吗!
public class SMSPopUpReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
if (intent.getAction().equals(SMSPopUpReceiver.ACTION)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus){
SmsMessage messages =
SmsMessage.createFromPdu((byte[]) pdu);
sb.append("Received SMS\nFrom: ");
sb.append(messages.getDisplayOriginatingAddress());
sb.append("\n----Message----\n");
sb.append( messages.getDisplayMessageBody());
}
}
Log.i(SMSPopUpReceiver.LOG_TAG,
"[SMSApp] onReceiveIntent: " + sb);
Toast.makeText
(context, sb.toString(), Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
}
}
【问题讨论】:
-
为什么不能使用
AlertDialog.Builder builder = new AlertDialog.Builder(this);是不是对this参考不满意?如果是这种情况,请尝试将其替换为对getApplicationContext()的调用。我不确定这是否是您遇到的问题。我觉得在这种情况下,对话框只会在 BroadcastReceiver 返回之前在屏幕上闪烁一秒钟。 -
不能使用 getApplicationContext() !
-
自发弹出一个对话框(从用户的角度来看)对我来说听起来像是糟糕的 UI 设计。为什么不使用通知?这就是他们的目的。
-
这是完整的例子,通过链接stackoverflow.com/a/41137562/4344659
标签: java android broadcastreceiver android-alertdialog