在广播接收器中创建AlertDialog?这可行吗?我正在开发一个应用程序,如果我收到短信,它将弹出一个对话框。我试图在BroadcastReceiver中编写此代码。但是我无法使用以下代码行 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 返回之前在屏幕上闪烁一秒钟。 - Will Tate