我有一个问题,我的应用程序一旦我在应用程序中并且按下我的手机上的“后退按钮”然后再次进入应用程序而继续崩溃...我想我正在处理某种状态或错误:
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”,但这会导致应用程序崩溃...
是的,我知道..这不是完整的代码..但是如果您需要更多的代码,请告诉我
提前致谢!
答案 0 :(得分:3)
当用户点击后退按钮时,您希望采取什么样的操作?在我的应用程序中,如果用户在主活动中而不在活动堆栈的深处,我会覆盖后退按钮以提示用户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();
}
}
}