如何从Main_Activity
课程开始BroadcastReceiver
?
我进行了搜索,发现了这段代码,但我不知道在哪里放我的包名。
Intent intent=new Intent();
intent.setClassName("com.package.my", "com.package.my.abc");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
我的包名是com.example.tes
。
记录:
01-15 08:49:23.800: E/AndroidRuntime(1326): FATAL EXCEPTION: main
01-15 08:49:23.800: E/AndroidRuntime(1326): Process: com.example.tes, PID: 1326
01-15 08:49:23.800: E/AndroidRuntime(1326): java.lang.RuntimeException: Unable to start receiver com.example.tes.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?
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2426)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ActivityThread.access$1700(ActivityThread.java:135)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.os.Handler.dispatchMessage(Handler.java:102)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.os.Looper.loop(Looper.java:136)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-15 08:49:23.800: E/AndroidRuntime(1326): at java.lang.reflect.Method.invokeNative(Native Method)
01-15 08:49:23.800: E/AndroidRuntime(1326): at java.lang.reflect.Method.invoke(Method.java:515)
01-15 08:49:23.800: E/AndroidRuntime(1326): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-15 08:49:23.800: E/AndroidRuntime(1326): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-15 08:49:23.800: E/AndroidRuntime(1326): at dalvik.system.NativeStart.main(Native Method)
01-15 08:49:23.800: E/AndroidRuntime(1326): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ContextImpl.startActivity(ContextImpl.java:1034)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ContextImpl.startActivity(ContextImpl.java:1021)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.content.ContextWrapper.startActivity(ContextWrapper.java:311)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.content.ContextWrapper.startActivity(ContextWrapper.java:311)
01-15 08:49:23.800: E/AndroidRuntime(1326): at com.example.tes.SMSReceiver.onReceive(SMSReceiver.java:47)
01-15 08:49:23.800: E/AndroidRuntime(1326): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
01-15 08:49:23.800: E/AndroidRuntime(1326): ... 10 more
答案 0 :(得分:2)
为什么不使用app context启动它:
Intent intent = new Intent (context, MainActivity.class);
intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity (intent);