[英]Android back-button causes crash?
我遇到一個問題,就是我在應用程序中遇到一次我的應用程序不斷崩潰的情況,然后按手機上的“后退按鈕”,然后再次進入該應用程序。.我猜我正在處理某種狀態或錯誤的消息:
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”相機,但是這也會導致應用崩潰。
是的,我知道..這不是完整的代碼..但是如果您需要更多代碼,請告訴我
提前致謝!
當用戶按下“后退”按鈕時,您想采取什么動作? 在我的應用程序中,如果用戶處於主要活動中而不是位於活動堆棧的深處,我將覆蓋AlertDialog
,以使用AlertDialog
提示用戶,詢問他們是否要退出應用程序,然后按是,我使用System.exit()
我打掃完房子后可以使用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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.