本文实例为大家分享了Android实现闪光灯效果的具体代码,供大家参考,具体内容如下
一、声明闪光灯的权限
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.FLASHLIGHT" />
注意:Camera权限6.0以上需要动态申请权限
二、具体的代码如下
package com.google.yang.myapplication; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * 闪光灯的控制 * * @author yang */ public class MainActivity extends AppCompatActivity { private Button open; private Button close; private Button openFlicker; private Button closeFlicker; private Camera camera; private Boolean isShanshuo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); open = (Button) this.findViewById(R.id.open); close = (Button) this.findViewById(R.id.close); openFlicker = (Button) findViewById(R.id.openFlicker); closeFlicker = (Button) findViewById(R.id.closeFlicker); open.setOnClickListener(openOnClickListener); close.setOnClickListener(closeOnClickListener); openFlicker.setOnClickListener(openFlickerOnClickListener); closeFlicker.setOnClickListener(closeFlickerOnClickListener); } /** * 打开手电筒 */ private OnClickListener openOnClickListener = new OnClickListener() { @Override public void onClick(View v) { open(); } }; /** * 关闭手电筒 */ private OnClickListener closeOnClickListener = new OnClickListener() { @Override public void onClick(View v) { close(); } }; /** * 开启闪烁 */ private OnClickListener openFlickerOnClickListener = new OnClickListener() { @Override public void onClick(View v) { isShanshuo = true; openFlicker.setEnabled(false); new Thread(new Runnable() { @Override public void run() { while (isShanshuo) { open(); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } close(); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }; /** * 关闭闪烁 */ private OnClickListener closeFlickerOnClickListener = new OnClickListener() { @Override public void onClick(View v) { isShanshuo = false; openFlicker.setEnabled(true); } }; /** * 打开闪光灯 * * @return */ private void open() { try { camera = Camera.open(); camera.startPreview(); Parameters parameters = camera.getParameters(); parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(parameters); } catch (Exception e) { e.printStackTrace(); } } /** * 关闭闪光灯 * * @return */ private void close() { try { Parameters parameters = camera.getParameters(); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(parameters); camera.release(); camera = null; } catch (Exception e) { e.printStackTrace(); } } }
XML界面很简单,四个按钮:
有兴趣的可以试一试,当作一个小工具收藏一下。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。