1

我有一个广播接收器,它会在收到新短信时提醒主要活动,每当我收到新短信时,应用程序就会崩溃。

Logcat 指出:

10-14 15:56:03.465: E/AndroidRuntime(27068): FATAL EXCEPTION: main
10-14 15:56:03.465: E/AndroidRuntime(27068): java.lang.RuntimeException: Unable to start receiver com.testapp.SMSReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

这是来自接收器的代码块,似乎导致错误

Intent passSMStoMain = new Intent(context, MainActivity.class);
                passSMStoMain.putExtra("SENDER", msg_from);
                passSMStoMain.putExtra("MESSAGE", msgBody);
                context.startActivity(passSMStoMain);//this line makes the app crash

我应该如何解决这个错误?

4

2 回答 2

0

试试这个:

Intent passSMStoMain = new Intent(context, MainActivity.class);
passSMStoMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
passSMStoMain.putExtra("SENDER", msg_from);
passSMStoMain.putExtra("MESSAGE", msgBody);
context.startActivity(passSMStoMain);
于 2013-10-14T15:51:20.370 回答
0

尝试getApplicationContext()

Intent passSMStoMain = new Intent(context, MainActivity.class);
passSMStoMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
passSMStoMain.putExtra("SENDER", msg_from);
passSMStoMain.putExtra("MESSAGE", msgBody);
context.getApplicationContext().startActivity(passSMStoMain);
于 2013-10-14T15:59:28.260 回答