【完美解决系列】Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

在Service中启动Activity,会报错如下:

Intent intent = new Intent(MyService.this, Main2Activity.class);
startActivity(intent);

                                                                           android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                               at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                               at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                               at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                               at realmusic.ace.com.myapplication.MyService$1.run(MyService.java:32)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:148)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

根据错误信息的提示,增加FLAG_ACTIVITY_NEW_TASK flag,即可解决问题。
解决方法:

ntent intent = new Intent(MyService.this, Main2Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(intent);

猜你喜欢

转载自blog.csdn.net/mvpstevenlin/article/details/80301530