代码来自于http://code.google.com/p/search-light/
不同类别的手机开启闪光灯的方法不一定相同,下面的代码适用于mb525,其他的手机我还没有试过.
package com.wjh.myset;
import java.io.PrintStream;
import java.lang.reflect.Method;
import android.os.IBinder;
public class MyFlashLight {
private Object svc = null;
private Method getFlashlightEnabled = null;
private Method setFlashlightEnabled = null;
@SuppressWarnings("unchecked")
public MyFlashLight() throws Exception{
try {
// call ServiceManager.getService("hardware") to get an IBinder for the service.
// this appears to be totally undocumented and not exposed in the SDK whatsoever.
Class sm = Class.forName("android.os.ServiceManager");
Object hwBinder = sm.getMethod("getService", String.class).invoke(null, "hardware");
// get the hardware service stub. this seems to just get us one step closer to the proxy
Class hwsstub = Class.forName("android.os.IHardwareService$Stub");
Method asInterface = hwsstub.getMethod("asInterface", android.os.IBinder.class);
svc = asInterface.invoke(null, (IBinder) hwBinder);
// grab the class (android.os.IHardwareService$Stub$Proxy) so we can reflect on its methods
Class proxy = svc.getClass();
// save methods
getFlashlightEnabled = proxy.getMethod("getFlashlightEnabled");
setFlashlightEnabled = proxy.getMethod("setFlashlightEnabled", boolean.class);
}
catch(Exception e) {
throw new Exception("LED could not be initialized");
}
}
public boolean isEnabled() {
try {
return getFlashlightEnabled.invoke(svc).equals(true);
}
catch(Exception e) {
return false;
}
}
public void enable(boolean tf) {
try {
setFlashlightEnabled.invoke(svc, tf);
}
catch(Exception e) {}
}
}