AppOpsManager接口startWatchingActive(int[], OnOpActiveChangedListener)
监听相机是否被使用
- 必须是系统应用
- 有
<uses-permission android:name="android.permission.WATCH_APPOPS"/>
权限 - API>=30
反射调用startWatchingActive(int[], OnOpActiveChangedListener):
private void monitorCamera() {AppOpsManager mAppOps = (AppOpsManager) getSystemService(APP_OPS_SERVICE);try {Class appOpsManagerCls = Class.forName(AppOpsManager.class.getName());Field OP_CAMERA = appOpsManagerCls.getField("OP_CAMERA");DebugLog.d("OP_CAMERA " + OP_CAMERA.get(mAppOps));Method method = appOpsManagerCls.getMethod("startWatchingActive", int[].class, AppOpsManager.OnOpActiveChangedListener.class);method.setAccessible(true);method.invoke(mAppOps, new int[]{(int) OP_CAMERA.get(mAppOps)}, opActiveChangedListener);} catch (Exception e) {DebugLog.e("error " + e.getMessage());}//不用时,注销监听//mAppOps.stopWatchingActive(opActiveChangedListener);
}
//监听相机使用
AppOpsManager.OnOpActiveChangedListener opActiveChangedListener = new AppOpsManager.OnOpActiveChangedListener() {@Overridepublic void onOpActiveChanged(@NonNull String op, int uid, @NonNull String packageName, boolean active) {DebugLog.d("packageName " + packageName + " active " + active);}
};