gpt4 book ai didi

Android后退按钮导致崩溃?

转载 作者:行者123 更新时间:2023-11-29 18:14:13 28 4
gpt4 key购买 nike

我有一个问题,我的应用程序在我进入应用程序并按下手机上的“后退按钮”然后再次进入应用程序后一直崩溃。我猜我正在处理某种状态或错误:

package com.animeus;

import com.animeus.Factories.CameraDialogsFactory;
import com.animeus.Factories.CameraFactory;
import com.animeus.Services.CameraService;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class LightBulbActivity extends Activity {
/** Called when the activity is first created. */
Camera c;

//Application starts here
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadComponentsToUse();
setComponentEvents();

if (c == null)
CameraDialogsFactory.GetNoCameraFoundDialog(this).show();
else
setComponentEvents();
}

//Sets all the components events
private void setComponentEvents() {
View v = (View)findViewById(R.id.LightBulbView);
v.setOnTouchListener(new View.OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
triggerLightEvent(event.getAction());
return false;
}
});
}

//Turns the led on or off
private void triggerLightEvent(int currentevent) {
if (currentevent == MotionEvent.ACTION_DOWN)
CameraService.turnLedLightOn(c);
else if (currentevent == MotionEvent.ACTION_UP)
{
CameraService.turnLedLightOff(c);
}
}

//Loads the "global" components we are supposed to use
private void loadComponentsToUse() {
c = CameraFactory.getCamera();
}

//Called once the activity ain't visible for the user anymore
@Override
public void onStop() {
super.onStop();
}


@Override
public void onPause() {
super.onPause();
}


@Override
public void onResume() {
super.onResume();
}
}

有什么想法吗?我还尝试在“onPause”和“onStop”上释放相机,然后重新创建“onResume”相机,但这也会导致应用程序崩溃...

是的,我知道..这不是完整的代码..但如果您需要更多代码,请告诉我

提前致谢!

最佳答案

当用户点击后退按钮时,您希望执行哪种操作?在我的应用程序中,如果用户处于主要 Activity 中并且不在 Activity 堆栈的深处,我会覆盖后退按钮以使用 AlertDialog 提示用户,询问他们是否要退出应用程序,然后是否退出他们按是我在打扫房间后使用 System.exit() 可以说是我创建的一种方法,它首先杀死并使所有东西无效。

您可以像这样覆盖后退按钮:

@Override
public void onBackPressed(){
super.onBackPressed();
cleanHouse();
System.exit(0);
}

你也可以把它放在你的 onPause() 中:

@Override
protected void onPause() {
super.onPause();
try{
cam.camera.release();
}catch(NullPointerException e){
e.printStackTrace();
try{
cam.camera.unlock();
}catch(NullPointerException f){
f.printStackTrace();
}
}
}

关于Android后退按钮导致崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9018917/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com