private ToggleButton toggleButton;
private Camera m_Camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.handlight);
toggleButton = (ToggleButton)this.findViewById(R.id.toggleButton1);
toggleButton.setOnClickListener(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
@Override
public void onClick(View v) {
ToggleButton tb = (ToggleButton)v;
if(!tb.isChecked()){
PackageManager pm= this.getPackageManager();
FeatureInfo[] features=pm.getSystemAvailableFeatures();
for(FeatureInfo f : features)
{
if(PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) //判断设备是否支持闪光灯
{
if ( null == m_Camera )
{
m_Camera = Camera.open();
}
Camera.Parameters parameters = m_Camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
m_Camera.setParameters( parameters );
m_Camera.startPreview();
toggleButton.setBackgroundColor(0x30ffffff);
}
}
}else{
if ( m_Camera != null )
{
m_Camera.stopPreview();
m_Camera.release();
m_Camera = null;
}
toggleButton.setBackgroundColor(0xffffffff);
}
}
}
handlight.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ToggleButton android:id="@+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:checked="true"
android:text="ToggleButton"/>
</LinearLayout>
需要加上权限
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.hardware.camera"/>
注意:并不是所有的设备都支持
网上还有一种说法是调用系统隐藏api,不过我试了没反应,可能是系统版本问题,备份一下
用IHardwareService直接控制
Android1.5以前是直接提供这个接口的,之后呢,需要我们自己来做一下。
在你的项目中新建一个包Android.os,新建一个IHardwareService.aidl文件,内容如下:
- package android.os;
- /** {@hide} */
- interface IHardwareService
- {
- // obsolete flashlight support
- boolean getFlashlightEnabled();
- void setFlashlightEnabled(boolean on);
- }
然后在你的程序中引入
- import android.os.IHardwareService;
- /**
- * 设置闪光灯的开启和关闭
- * @param isEnable
- * @author linc
- * @date 2012-3-18
- */
- private void setFlashlightEnabled(boolean isEnable)
- {
- try
- {
- Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
- IBinder binder = (IBinder) method.invoke(null, new Object[] { "hardware" });
- IHardwareService localhardwareservice = IHardwareService.Stub.asInterface(binder);
- localhardwareservice.setFlashlightEnabled(isEnable);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
这样就可以开启闪光灯了。要使用的权限: