一、引子
曾經遇到一個問題,使用View的Context變量調用startActivity()方法,出現一個異常:“Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?”。百度了下異常的原因,是由於調用startActivity()的Context爲Application,而非Activity。
在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);
}
其中getLaunchTaskId方法相關信息如下:
private int mLaunchTaskId = -1;
public int getLaunchTaskId() {
return mLaunchTaskId;
}
/**
* The task id the activity should be launched into.
* @hide
*/
private static final String KEY_LAUNCH_TASK_ID = "android.activity.launchTaskId";
public ActivityOptions(Bundle opts) {
// ...
mLaunchTaskId = opts.getInt(KEY_LAUNCH_TASK_ID, -1);
// ...
}
可以看到,在intent未使用Intent.FLAG_ACTIVITY_NEW_TASK,且android Api在24以下或27以上的機型上,如果bundle爲空,或bundle所在的taskId爲-1,會報異常。這樣可以大致推測,使用Application的Context啓動activity,由於沒有Activity的taskId信息,無法確定新Activity的taskId,所以拋出異常。
那爲什麼View的Context有時是Activity,有時是Application呢?
二、查找
(一)從LayoutInflater.from(Context context)方法開始
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return LayoutInflater;
}
需要了解下Context、ContextImpl、ContextWrapper相關知識。
Context.getSystemService其實直接調用了ContextImpl類的getSystemService方法
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
直接調用了SystemServiceRegistry類的getSystemService()方法
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
其中SYSTEM_SERVICE_FETCHERS是SystemServiceRegistry類的靜態變量,它的初始化中包含
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});
ctx.getOuterContext()其實就是LayoutInflater.from()傳入的Context參數。
看下CachedServiceFetcher類
static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
@Override
public final T getService(ContextImpl ctx) {
final Object[] cache = ctx.mServiceCache;
// Return it if we already have a cached instance.
T service = (T) cache[mCacheIndex];
if (service != null || gates[mCacheIndex] == ContextImpl.STATE_NOT_FOUND) {
return service;
}
T service = null;
try {
service = createService(ctx);
newState = ContextImpl.STATE_READY;
} catch (ServiceNotFoundException e) {
onServiceNotFound(e);
}
return service;
}
public abstract T createService(ContextImpl ctx) throws ServiceNotFoundException;
}
從傳入的ContextImpl中獲取該Context是否已經生成了LayoutInflater,如果未生成,則通過createService()方法創建。
所以SystemServiceRegistry類的getSystemService()返回的是PhoneLayoutInflater,使用的LayoutInflater.from()方法傳入的Context變量。繞了一圈,從Context繞到ContextImpl,又繞回到了Context。
(二)拿到LayoutInflater,可以去inflate()了
雖然上一步中,生成的是PhoneLayoutInflater,但inflate()方法使用的仍然是基類LayoutInflater的inflate()方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
看下inflate()方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
final String name = parser.getName();
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
return result;
}
}
其中關注下createViewFromTag()方法,
final Context inflaterContext = mContext;
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
傳入的Context參數爲LayoutInflater的mContext變量。
三、結論
View的Context與LayoutInflater.from()傳入的Context保持一致。