在我的应用程序中,当从1902年收到短信时,我希望AlertDialog能够实现。 我有BroadcastReciever Running
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + phoneNumber + "; message: " + message);
if (TextUtils.equals(currentMessage.getOriginatingAddress(), "1902")) {
// Show Alert
MainActivity actv1= new MainActivity();
actv1.Dialog(message);
}
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
在主要活动中我有Void:
public void Dialog(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Title123");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
Log.i("test2", message);
builder.show();
}
但是当收到短信没有发生任何事情时,专家可以告诉我们有什么问题吗?
答案 0 :(得分:0)
您已创建MyActivity以用作上下文而非已提供的上下文
if (TextUtils.equals(currentMessage.getOriginatingAddress(), "1902"))
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title123");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
builder.show();
}
注意强>
MainActivity actv1= new MainActivity(); // This is wrong
您无法使用新操作员自行创建任何活动,Android操作创建活动只需传递创建活动的意图。