package me.yoqi.flashlight.utils;

import java.lang.reflect.Method;

import android.os.IBinder;

/**
 * 闪光灯工具
 * @author liuyuqi
 *
 */
public class DroidLED {
	
	private Object svc = null;
	private Method getFlashlightEnabled = null; //系统flash闪光灯get方法
	private Method setFlashlightEnabled = null;

	/** 构造函数
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public DroidLED() throws Exception {
		try {
			Class sm = Class.forName("android.os.ServiceManager");
			Object hwBinder = sm.getMethod("getService", String.class).invoke(
					null, "hardware");
			Class hwsstub = Class.forName("android.os.IHardwareService$Stub");
			Method asInterface = hwsstub.getMethod("asInterface",
					android.os.IBinder.class);
			svc = asInterface.invoke(null, (IBinder) hwBinder);
			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) {
		}
	}
}