Android开启闪光灯的方法 Android打开手电筒功能
前言
众所周知,安卓的手电筒功能无非是开启手机的闪光灯,既然开启闪光灯就必须要与相机关联。
代码
写了个小工具,一个文件搞定。
publicclassFlashUtils{
privatestaticFlashUtilsutils;
privatestaticCameracamera;
publicstaticbooleanmIsOpen=true;
//使用单例模式在这里初始化相机
publicstaticFlashUtilsgetInstance(){
if(utils==null){
utils=newFlashUtils();
}
try{
if(camera==null){
camera=Camera.open();
}
}catch(Exceptione){
if(camera!=null){
camera.release();
}
camera=null;
}
returnutils;
}
//参考二维码工具的闪光灯
publicvoidswitchFlash(){
try{
Parametersparameters=camera.getParameters();
if(mIsOpen){
if(parameters.getFlashMode().equals("torch")){
return;
}else{
parameters.setFlashMode("torch");
}
}else{
if(parameters.getFlashMode().equals("off")){
return;
}else{
parameters.setFlashMode("off");
}
}
camera.setParameters(parameters);
}catch(Exceptione){
finishFlashUtils();
}
mIsOpen=!mIsOpen;
}
//页面销毁的时候调用此方法
publicvoidfinishFlashUtils(){
if(camera!=null){
camera.stopPreview();
camera.release();
}
camera=null;
}
}
6.0及其以上亲测可用,需手动打开权限。
5.0以下暂未测试。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。