在android中打开闪光灯的方法有两种,一种是获取硬件服务,通过反射的方式来操作闪光灯。另外一种是获得Camera对象,通过设置Camera的参数来操作闪光灯。一下是一个操作闪光灯的工具类:实现了两种方式操作闪光灯。通过switchFlashlight方法是通过反射的方式操作,通过turnLightOn,turnLightOff方法操作是通过设置Camera来操作闪关灯的。
为了达到将功耗的目的,需要把闪光灯打开的方式从操作Camera改为直接获得硬件结点进行操作的方式。成立由驱动工程师和应用工程师组成的小组,设计出通过在应用中添加额外放射代码,以及在系统服务CameraService中添加直接操作硬件结点/dev/flashlight的方式 控制FlashLight开关的方案,最终顺利完成功耗电流测试。
private static final Object iHardwareService;
private static final Method setFlashEnabledMethod;
static {
iHardwareService = getHardwareService(); //静态代码块 获得Method方法 获得ICameraService的接口
setFlashEnabledMethod = getSetFlashEnabledMethod(iHardwareService);
if (iHardwareService == null) {
Log.v(TAG, "This device does supports control of a flashlight");
} else {
Log.v(TAG, "This device does not support control of a flashlight");
}
}
/**
* 通过反射来操作闪光灯
*/
private static Object getHardwareService() {
// 反射获得Class对象
Class<?> serviceManagerClass = maybeForName("android.os.ServiceManager");
if (serviceManagerClass == null) {
return null;
}
//从Class对象获得Method对象
Method getServiceMethod = maybeGetMethod(serviceManagerClass, "getService", String.class);
if (getServiceMethod == null) {
return null;
}
// 从Method 对象获得cameraservice服务的Object对象
Object hardwareService = invoke(getServiceMethod, null, "cameraservice");
if (hardwareService == null) {
return null;
}
// 获得ICameraService的Stub的Class
Class<?> iHardwareServiceStubClass = maybeForName("android.os.ICameraService$Stub");
if (iHardwareServiceStubClass == null) {
return null;
}
//获得 ICameraService的asInterface 最终回返回一个客户端的操作类
Method asInterfaceMethod = maybeGetMethod(iHardwareServiceStubClass, "asInterface", IBinder.class);
if (asInterfaceMethod == null) {
return null;
}
return invoke(asInterfaceMethod, null, hardwareService);
}
public static void switchFlashlight(boolean active) {
setFlashlight(active);
}
static void disableFlashlight() {
setFlashlight(false);
}
private static void setFlashlight(boolean active) {
if (iHardwareService != null) {
invoke(setFlashEnabledMethod, iHardwareService, active);
}
}
}
private static Object invoke(Method method, Object instance, Object... args) {
try {
return method.invoke(instance, args);
} catch (Exception e) {
Log.w(TAG, "Unexpected error while invoking " + method, e);
return null;
}
}
private static Method getSetFlashEnabledMethod(Object iHardwareService) {
if (iHardwareService == null) {
return null;
}
Class<?> proxyClass = iHardwareService.getClass();
return maybeGetMethod(proxyClass, "setFlashlightEnabled", boolean.class);
}
private static Class<?> maybeForName(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException cnfe) {
// OK
return null;
} catch (Exception re) {
re.printStackTrace();
Log.w(TAG, "Unexpected error while finding class " + name, re);
return null;
}
}
闪光灯降功耗方案
最新推荐文章于 2020-12-31 20:41:49 发布