android---护眼灯和兼容性高的手电筒实现
程序主要有两个功能,一是护眼灯,二是手电筒,然而手电筒兼容性解决办法就是加入异常控制,避免各种异常占用启动不了手电筒.
程序主界面,没有美化,只实现基本功能.
部分代码:
护眼蒙板主要代码
private void CreateView() {
mWindowManager = (WindowManager) getApplication()
.getSystemService(Context.WINDOW_SERVICE);
wmParams = new WindowManager.LayoutParams();
// 电话窗口。它用于电话交互(特别是呼入)。它置于所有应用程序之上,状态栏之下。
wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
//设置图片格式,效果为背景透明
wmParams.format = PixelFormat.RGBA_8888;
// 设置浮动窗口不可聚焦(实现操作除浮动窗口外的其他可见窗口的操作)
wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
//调整悬浮窗显示的停靠位置为左侧置顶
wmParams.gravity = Gravity.LEFT | Gravity.TOP;
wmParams.x = 0;
wmParams.y = 0;
//设置悬浮窗口长宽数据
wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
wmParams.height = WindowManager.LayoutParams.MATCH_PARENT;
v = new MyView(getApplicationContext());
mWindowManager.addView(v, wmParams);
}
手电筒主要代码
/**
* 打开或者关闭手电筒
*/
private View.OnClickListener flash = new View.OnClickListener() {
@Override
public void onClick(View v) {
// 先判断是否有闪光灯
if (!getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
Toast.makeText(MainActivity.this, "当前设备没有闪关灯", Toast.LENGTH_LONG).show();
return;
}
if (flashstate){
close();
btnstartflash.setText("开启手电筒");
}else if (!flashstate){
open();
btnstartflash.setText("关闭手电筒");
}
}
};
private void initflashmode() {
try {
camera = Camera.open();
camera.setPreviewTexture(new SurfaceTexture(0));
} catch (IOException e) {
close();
}
if (camera != null) {
parameters = camera.getParameters();
previousflashmode = parameters.getFlashMode();
}
if (previousflashmode == null) {
previousflashmode = Camera.Parameters.FLASH_MODE_OFF;
}
}
//关闭相机
private void close() {
if (camera!=null){
parameters.setFlashMode(previousflashmode);
camera.setParameters(parameters);
camera.release();
camera = null;
flashstate = false;
}
}
//打开相机
private void open(){
if (camera==null) {
initflashmode();
}
if (camera!=null){
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
flashstate = true;
}
}
完整代码可以联系我1015315668@qq.com
版权声明:本文为博主原创文章,未经博主允许不得转载。