*本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布
今天开发过程中被测试提了个bug.原来我一不注意,用Service的Context启动Activity导致报错(我用我自己的手机可以启动).
java.lang.RuntimeException: Error receiving broadcast Intent { act=com....}
...
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?
最终解决办法就是给Intent加个FLAG_ACTIVITY_NEW_TASK的flag就能顺利启动了
intent.addFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
这里先上一张图
可以看出,除了Activity以外,其他组件都是不允许去启动Activity的.但今天用低端三星机(Android4.4)启动报错.而用我的P20Pro徕卡三摄(Android8.0)却能正常启动.这不是跟这张图说的不一样吗...
那就来看看源码是怎么写的吧
首先看下Activity是怎么启动的.当用Activity启动Activity时会调用Activity.startActivity(intent)
Activity
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
//最终会调
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
......//省略无关代码
} else {
......//省略无关代码
}
}
这里的mParent是ActivityThread.scheduleLaunchActivity()里的ActivityClientRecord传给他的,默认为空.这里的Instrumentation.startActivity()就表示开始启动Activity了,具体启动流程就不在本篇里详细说明了,之前写过一篇缕清楚Activity启动流程的文章,给个传送门.这个启动过程比较繁琐,我是建议大家自己找个源码一步一步跟下去会学的比较扎实.
那么其他组件启动Activity的流程是怎样呢?
像Service,BroadcastReceiver,Application等都是ContextWrapper的子类,调用startActivity()时会调用ContextWrapper的startActivity()
ContextWrapper
@Override
public void startActivity(Intent intent) {
mBase.startActivity(intent);
}
这个mBase就是ContextImpl.这个ContextImpl是在ActivityThread里赋值的:
Activity-->ActivityThread::performLaunchActivity()
Service-->ActivityThread::handleCreateService()
Application-->LoadedApk::makeApplication()
有兴趣的同学自行查看.
那我们来看下ContextImpl的startActivity().
先看低版本的
Android4.4 api-19
ContextImpl
@Override
public void startActivity(Intent intent) {
warnIfCallingFromSystemProcess();
startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity)null, intent, -1, options);
}
很简单,就是非Activity的Context启动Activity时如果不给intent设置FLAG_ACTIVITY_NEW_TASK就会报错.
然后再来看高版本的:
Android8.0 api-27
ContextImpl
@Override
public void startActivity(Intent intent) {
warnIfCallingFromSystemProcess();
startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
// Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
// generally not allowed, except if the caller specifies the task id the activity should
// be launched in.
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& options != null && ActivityOptions.fromBundle(options).getLaunchTaskId() == -1) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}
跟旧版本的代码相比,这里多了个options的非空判断(options != null),关键就在这里.
由于这里options传的就是null,于是就跳过了这个异常.那么,这里的逻辑是"&&",有一个不成立就算失败,那么我们不设置FLAG_ACTIVITY_NEW_TASK就能顺利的启动Activity了.
这里的注释翻译下是:从Activity外部(Service,BroadcastReceiver,Application等)不设置FLAG_ACTIVITY_NEW_TASK是不能启动Activity的,除非调用者指定Activity要启动的task的Id.
可是我也并没有指定task的id就能成功启动了啊,这应该算Android系统的一个bug吧.看来谷歌开发人员也有犯浑的时候.
这段代码我查了下是Android7.0(api24)开始有的,也就是说Android6.0或以下系统还是不能启动的,我测试了下确实是这样.
以下是Android7.0的测试:
以下是Android6.0的测试:
逻辑就是MainActivity点击按钮启动TService,然后TService启动SubActivity
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
startService(new Intent(this, TService.class));
}
TService:
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, SubActivity.class);
intent.putExtra("data","从Service启动的Activity");
startActivity(intent);
}
SubActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
TextView textView = findViewById(R.id.tv);
String data = getIntent().getStringExtra("data");
textView.setText(data);
}
我们最终得出结论Android7.0和Android8.0里Service,BroadcastReceiver,Application等都是可以启动Activity的.
------------------2018.11.1--------------------
今天我又看了下Android9.0的源码,貌似已经修复了这个bug
ContextImpl
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
// Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
// generally not allowed, except if the caller specifies the task id the activity should
// be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
// maintain this for backwards compatibility.
final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& (targetSdkVersion < Build.VERSION_CODES.N
|| targetSdkVersion >= Build.VERSION_CODES.P)
&& (options == null
|| ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}
这里已经改为&&options == null了.应该已经修复了.我目前没有测试的条件,有兴趣的同学可以去测试一下,Android9.0中Service已经不能直接启动Activity了.