Android 打开闪光灯(手电筒)

package com.example.openBackLight;



import android.app.Activity;

import android.hardware.Camera;

import android.os.Bundle;

import android.view.View;

import android.hardware.Camera.Parameters;

import android.widget.Button;



public class MyActivity extends Activity {

    private Button button;

    private Camera camera;

    private Parameters parameters;

    public boolean hasClosed = true; // 定义开关状态,状态为false,打开状态,状态为true,关闭状态



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        

        button = (Button) findViewById(R.id.button);

    }



    public void toggleLight(View view) {

        if (hasClosed) {

            camera = Camera.open();

            parameters = camera.getParameters();

            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);// 开启

            camera.setParameters(parameters);

            button.setText("关闭闪光灯");

            hasClosed = false;

        } else {

            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);// 关闭

            camera.setParameters(parameters);

            button.setText("开启闪光灯");

            hasClosed = true;

            camera.release();

        }

    }

    

}

布局文件很简单,就一个button,点击的时候会调用toggleLight()方法.

要加入以下权限:

    <uses-permission android:name="android.permission.FLASHLIGHT" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />

 

你可能感兴趣的:(android)