今天做了一个悬浮效果,从悬浮控件跳转Activity时报错Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
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:682)
at android.app.ContextImpl.startActivity(ContextImpl.java:669)
at android.content.ContextWrapper.startActivity(ContextWrapper.java:341)
at com.geotmt.collection.task.service.FloatButtonService$1.onClick(FloatButtonService.java:75)
at android.view.View.performClick(View.java:5215)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5597)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:771)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:649)
原因分析和解决方法
因为我是从一个服务FloatButtonService
中向Activity跳转,用的是Context
的startActivity
方法,最终点的是用的是Context
的子类ContextImpl
的startActivity
,那我们就从这里入手,看看ContextImpl
的startActivity
的逻辑
如图错误的地方找到了,总结一下原因使用Context的startActivity方法,就需要开启一个新的的task,否则就会抛出上面的异常,注意(我们平时在activity中使用startActivity没有报错,是因为Activity重写了Context的startActivity方法,因此无任何限制)
解决办法
Intent携带一个Intent.FLAG_ACTIVITY_NEW_TASK
,即可解决