代码如下:
Java代码:
package com.example.x.newlight;
import android.app.Activity;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements View.OnClickListener {
private ToggleButton toggleButton;
private Camera m_Camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initLight();
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 toggleButton = (ToggleButton) v;
if (!toggleButton.isChecked()){
initLight();
m_Camera.startPreview();
}else {
m_Camera.stopPreview();
m_Camera.release();
m_Camera = null;
}
}
private void initLight() {
PackageManager pm = this.getPackageManager();
FeatureInfo[] features = pm.getSystemAvailableFeatures();
for (FeatureInfo f : features) {
if (PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) //判断设备是否支持闪光灯
{
System.out.println("支持");
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);
} else {
System.out.println("不支持");
}
}
}
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.x.newlight.MainActivity">
<ToggleButton android:id="@+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:checked="true"
android:text="ToggleButton"/>
</RelativeLayout>
权限:
<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"/>