继承上下文类
前端时间重构代码需要设置一个类为上下文,在此记录:
public class MyContext extends ContextWrapper {
public XContextWrapper(Context base) {
super(base);
}
public void attach(Context base) {
attachBaseContext(base);
}
}
实现MyContext对象后需要调用attach方法实现上下文的功能,传入一个实现了功能的上下文,如Application的上下文。
利用meta-data实现默认对象
此方法类似多渠道打包。利用meta-data标签在Application类里完成创建某个类为默认对象,达到默认启动的目的:
AndroidManifest中:
<meta-data android:name="xxxxxx" android:value="com.example.xxxxxx"/>
创建一个继承于Application的类:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
try {
ApplicationInfo applicationInfo = getPackageManager()
.getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
String className = applicationInfo.metaData.getString("xxxxxx");
try {
Class launcherClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
最后要在AndroidMainfest文件里设置Application标签:
<application
android:name="x.core2.utils.XBaseVRApplication"
...
/>