本次排查Bug的fragment基于AndroidX1.1.0
線上bugly報了一個Could not find Fragment constructor,先看一下Fragment的構造函數
/**
* Constructor used by the default {@link FragmentFactory}. You must
* {@link FragmentManager#setFragmentFactory(FragmentFactory) set a custom FragmentFactory}
* if you want to use a non-default constructor to ensure that your constructor
* is called when the fragment is re-instantiated.
*
* <p>It is strongly recommended to supply arguments with {@link #setArguments}
* and later retrieved by the Fragment with {@link #getArguments}. These arguments
* are automatically saved and restored alongside the Fragment.
*
* <p>Applications should generally not implement a constructor. Prefer
* {@link #onAttach(Context)} instead. It is the first place application code can run where
* the fragment is ready to be used - the point where the fragment is actually associated with
* its context. Some applications may also want to implement {@link #onInflate} to retrieve
* attributes from a layout resource, although note this happens when the fragment is attached.
*/
public Fragment() {
initLifecycle();
}
主要看一下注釋說明,如果你想要的使用非默認的構造函數,需要自己實現一個FragmentFactory去初始化,然后強烈推薦使用setArguments和getArguments存取參數。看了一下報錯的類,可以基本確定是使用了帶參數的構造函數
然后看一下報錯的位置,在Fragment里搜索could not find Fragment constructor
public static Fragment instantiate(@NonNull Context context, @NonNull String fname,
@Nullable Bundle args) {
try {
Class<? extends Fragment> clazz = FragmentFactory.loadFragmentClass(
context.getClassLoader(), fname);
Fragment f = clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.setArguments(args);
}
return f;
} catch (java.lang.InstantiationException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (NoSuchMethodException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": could not find Fragment constructor", e);
} catch (InvocationTargetException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": calling Fragment constructor caused an exception", e);
}
}
可以看到這里通過反射,調用了空的構造函數
Fragment f = clazz.getConstructor().newInstance();
但是對應的類沒有空的構造函數,所以拋出了這個異常。然后看一下初始的地方,是FragmentActivity在onCreate中調用的mFragments.restoreSaveState(p);
結論:
Fragment必須有一個無參public的構造函數,否則在數據恢復的時候,會報crash
ps:手動測試發現私有的構造函數無法通過該Constructor.newInstance方法調用