複製代碼 代碼如下:public class HandLightActivity extends Activity implements OnClickListener{
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();
}
}
這樣就可以開啟閃光燈了。要使用的許可權:
複製代碼 代碼如下:<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.HARDWARE_TEST" />