需求:
做一个手电筒APK,要求如下:
1:手电筒应用打开后需要有具体的界面打开和关闭按钮。按Home,Recent键保持长亮,按 Back键关闭
2:手电筒的状态必须和下拉栏的手电筒状态一致
3:手电筒打开和关闭,需要有一个弹框提醒用户确认或者取消,弹框风格请自定义view来写
4:APK要经过测试通过且代码规范方可视作完成
最终效果:
FlashlightActivity.java
package com.example.flashlight;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import com.example.flashlight.view.CustomDialog;
public class FlashlightActivity extends AppCompatActivity implements View.OnClickListener {
private static ImageView iv;
private CameraManager mCameraManager;
public static boolean isOpen = false;
private static final CameraManager.TorchCallback torchCallback = new CameraManager.TorchCallback() {
@Override
public void onTorchModeUnavailable(@NonNull String cameraId) {
super.onTorchModeUnavailable(cameraId);
}
@Override
public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
super.onTorchModeChanged(cameraId, enabled);
if (isOpen != enabled) {
if (isOpen) {
iv.setImageResource(R.drawable.off_img);
} else {
iv.setImageResource(R.drawable.on_img);
}
}
isOpen = enabled;
}
@Override
public void onTorchStrengthLevelChanged(@NonNull String cameraId, int newStrengthLevel) {
super.onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
}
};
@Override
public void onBackPressed() {
super.onBackPressed();
close();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv_led);
findViewById(R.id.on_btn).setOnClickListener(this);
findViewById(R.id.off_btn).setOnClickListener(this);
mCameraManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
mCameraManager.registerTorchCallback(torchCallback, new Handler());
mCameraManager.registerTorchCallback(new CameraManager.To
标签:demo,void,手电筒,cameraId,CameraManager,public,import,Android,android
From: https://blog.csdn.net/m0_70859331/article/details/136814487