android 手电筒电量低于15%,Android 手电筒(最强适配版)

网上很多手电筒的代码,然后整理了下

使用:不停的调用onAndoff就能开和关手电筒

isopen是开关状态,比如你可以用他来判断手电是否打开。

可以看到使用了单例模式和线程同步,原因是你只有一个灯泡。

那边看代码,边看注释吧

public class Flash {

private static Flash mFlash;

private static Camera mCamera = null;

private static Camera.Parameters mCameraParameters;

private static String previousFlashMode = null;

private static boolean isOpen = false;

private Flash() {

}

public static Flash getInstance() {

if (mFlash == null) {

mFlash = new Flash();

}

return mFlash;

}

public synchronized void open(Context context) {

if (context.getPackageManager().hasSystemFeature(

PackageManager.FEATURE_CAMERA_FLASH)) {//这里的判断证实是没有用的,不能用来判断手机是否有灯泡,已经加了我就再没删

try {

mCamera = Camera.open();

mCamera.setPreviewTexture(new SurfaceTexture(0));//这一句话很重要,不加的话在nexus 5上灯泡不亮

} catch (Exception e) {

close();

String mString = context.getApplicationContext().getResources()

.getString(R.string.device_unable);

Toast.makeText(context.getApplicationContext(), mString,

Toast.LENGTH_LONG).show();

//这里是打不开的情况,比如别人正在使用的灯泡,打不开用一个close关一次,下次就能打开了。

}

} else {

Toast.makeText(context,

context.getString(R.string.device_cannot_find),

Toast.LENGTH_LONG).show();

return;

}

if (mCamera != null) {

mCameraParameters = mCamera.getParameters();

previousFlashMode = mCameraParameters.getFlashMode();

}

if (previousFlashMode == null) {

// could be null if no flash, i.e. emulator

previousFlashMode = Camera.Parameters.FLASH_MODE_OFF;

}

}

public synchronized void close() {//关灯,就是用完之后清除一下camera对象,不然会影响其他设备的正常使用

if (mCamera != null) {

mCameraParameters.setFlashMode(previousFlashMode);

mCamera.setParameters(mCameraParameters);

mCamera.release();

mCamera = null;

isOpen = false;

}

}

public synchronized void onAndOff(Context context) {//开\关都在这里调

try {

if (isOpen) {

off();

} else if (!isOpen) {

on(context);

}

// send broadcast for widget

//调完之后可以通知界面更新

} catch (RuntimeException e) {

Toast.makeText(context, R.string.device_unavailable,

Toast.LENGTH_SHORT).show();

}

}

public synchronized void on(Context context) {

if (mCamera == null) {

open(context);

}

if (mCamera != null) {

mCameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

mCamera.setParameters(mCameraParameters);

mCamera.startPreview();

isOpen = true;

}

}

public synchronized void off() {

if (mCamera != null) {

mCamera.stopPreview();

mCameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);

mCamera.setParameters(mCameraParameters);

isOpen = false;

}

close();

}

public boolean isOpen() {

return isOpen;

}

public void setOpen(boolean isOpen) {

Flash.isOpen = isOpen;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值