Android闪光灯的打开与关闭

Android闪光灯的打开代码:

camera = Camera.open();
Parameters params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview(); // 开始亮灯
img_main.setBackgroundColor(Color.WHITE);
isopen = true;
Toast.makeText(getApplicationContext(), "手电筒已打开", 0).show();

Android闪光灯的关闭代码:

camera.stopPreview(); // 关掉亮灯
camera.release(); // 关掉照相机
img_main.setBackgroundResource(R.drawable.main_body);
isopen = false;
Toast.makeText(getApplicationContext(), "手电筒已关闭",
                            Toast.LENGTH_SHORT).show();

Android闪光灯的权限设置:

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

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

MainActivity完整代码:

package com.j*****.flashlight;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private boolean isopen = false;
    private Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        View view = View.inflate(this, R.layout.main, null);
        setContentView(view);
        final TextView img_main = (TextView) findViewById(R.id.main_img);

        img_main.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("ShowToast")
            @Override
            public void onClick(View v) {
                if (!isopen) {
                    camera = Camera.open();
                    Parameters params = camera.getParameters();
                    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    camera.setParameters(params);
                    camera.startPreview(); // 开始亮灯
                    img_main.setBackgroundColor(Color.WHITE);
                    isopen = true;
                    Toast.makeText(getApplicationContext(), "手电筒已打开", 0).show();
                } else {
                    camera.stopPreview(); // 关掉亮灯
                    camera.release(); // 关掉照相机
                    img_main.setBackgroundResource(R.drawable.main_body);
                    isopen = false;
                    Toast.makeText(getApplicationContext(), "手电筒已关闭",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

即可;

你可能感兴趣的:(android,手电筒,闪光灯)