Android P 之后,谷歌限制开发者调用非官方的API方法或者接口(使用@hide注解的系统源码),意味着用反射直接调用的源码就会有出现提示弹窗。非SDK接口指的是Android系统内部使用、并未提供在SDK中的接口,开发者可能通过Java反射、JNI等技术来调用这些接口。但是非SDK接口没有任何官方文档,必须查看源代码才能理解其行为逻辑。谷歌旨在提示开发者尽量少使用反射只调用系统API,以免造成不必要的麻烦。但是项目中,有些功能实现需要用到如何避免弹窗呢?甚至有些依赖的第三方类库,用到了怎么办?
源码是Java写的,万物皆可反射,所以可以用反射的逻辑来屏蔽启动弹窗。
public class MyApplication extends Application {
private static MyApplication sInstance;
private static Context applicationContext;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
applicationContext = this;
disableAPIDialog();
}
public static MyApplication getInstance(){
return sInstance;
}
public static Context getContext(){
return applicationContext;
}
/**
* 反射 禁止弹窗
*/
private void disableAPIDialog(){
if (Build.VERSION.SDK_INT < 28)return;
try {
Class cla = Class.forName("android.app.ActivityThread");
Method currentActivityThread = cla.getDeclaredMethod("currentActivityThread");
currentActivityThread.setAccessible(true);
Object activityThread = currentActivityThread.invoke(null);
Field mHiddenApiWarningShown = cla.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在app初始化时提调用一次,就不会再出现弹窗。
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/logo"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">