我有一个广播接收器,可以在收到新短信时提醒主要活动,每当我收到新短信时应用程序崩溃。
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
我该如何解决此错误?
答案 0 :(得分: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);
答案 1 :(得分: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);