嗨,我正在寻找手电筒应用程序源代码,我修改了一点点当我最小化应用程序手电筒将关闭所以我只使用onDestroy()方法关闭应用程序状态但是当我关闭时,有时应用程序甚至不工作它显示闪光灯但不打开闪光灯 这就是我做的事情
public class MainActivity extends AppCompatActivity {
Button button;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton imgbutton = (ImageButton)findViewById(R.id.imageButton);
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
getCamera();
//button.setOnClickListener(new View.OnClickListener() {
imgbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
Toast.makeText(MainActivity.this, "Flash OFF!", Toast.LENGTH_SHORT).show();
imgbutton.setImageResource(R.drawable.light_off);
} else {
turnOnFlash();
Toast.makeText(MainActivity.this, "Flash ON!", Toast.LENGTH_SHORT).show();
imgbutton.setImageResource(R.drawable.light_on);
}
}
});
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
}catch (Exception e) {
}
}
}
private void turnOnFlash() {
if(!isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
protected void onDestroy(){
if(camera!=null){
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
} }
答案 0 :(得分:1)
你忘了覆盖:
onStop()
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
onResume()
@Override
protected void onResume() {
super.onResume();
if(hasFlash)
turnOnFlash();
}
获取hasFlash
我建议您将其放入onCreate()
以了解设备是否有闪存
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
onPause()
@Override
protected void onPause() {
super.onPause();
turnOffFlash();
}
顺便说一下,你重复了代码......
答案 1 :(得分:0)
使用onPause()
和onResume()
方法并在此处执行您的代码。
@Override
protected void onPause() {
super.onPause();
//Your code
}
@Override
protected void onResume() {
super.onResume();
//Your code
}