2013-10-22 28 views
0

我有一個應用程序在模擬器和手機中運行良好,但如果我們通過單擊手機的退出按鈕(而不是從應用程序)關閉應用程序。幾個小時後我們重新打開應用程序,它從應用程序中間打開(而不是從第一個屏幕)。使用該應用程序一段時間後,它會被掛起並顯示消息'不幸的是,應用程序已停止'。這是移動問題還是應用程序問題。如果應用程序未關閉(在後臺運行),是否會導致應用程序崩潰?

+0

請在你的問題中加入代碼 – Darshak

+1

至少你應該發佈貓日誌錯誤日誌.. –

+0

雅是多數民衆贊成真的,但其工作正常在模擬器,有些時候(很少)我在mobile.so這個消息我不能看到logcat。 – LMK

回答

1

我建議您閱讀Activity文檔。 Android OS擁有自己的應用程序生命週期管理。 每個活動都保持「活着」,直到它的onDestroy被調用。例如,操作系統可以將活動保持幾個小時,然後在沒有足夠內存執行其他任務時將其停用。

在你的情況下會發生什麼事是最有可能的是,同樣的活動重播,當你打開你的應用程序再次(在模擬器中活動可能被打死之前),你在狀態不好是因爲一些可能的對象被處置或重新初始化。

正確的做法是使用其他一些狀態回調,例如onPause/Resume來分配/處理活動使用的資源。

你的代碼可能是這樣的:

public class SomeActivity extends Activity 
{ 
    public void onCreate() 
    { 
     super.onCreate(); 
     // Do some object initialization 
     // You might assume that this code is called each time the activity runs. 
     // THIS CODE WILL RUN ONLY ONCE UNTIL onDestroy is called. 
     // The thing is that you don't know when onDestry is called even if you close the. 
     // Use this method to initialize layouts, static objects, singletons, etc'.  
    } 

    public void onDestroy() 
    { 
     super.onDestroy(); 
     // This code will be called when the activity is killed. 
     // When will it be killed? you don't really know in most cases so the best thing to do 
     // is to assume you don't know when it be killed. 
    } 
} 

您的代碼應該是這個樣子:

public class SomeActivity extends Activity 
{ 
    public void onCreate() 
    { 
     super.onCreate(); 
     // Initialize layouts 
     // Initialize static stuff which you want to do only one time 
    } 

    public void onDestroy() 
    { 
     // Release stuff you initialized in the onCreate 
    } 

    public void onResume() 
    { 
     // This method is called each time your activity is about to be shown to the user,   
     // either since you moved back from another another activity or since your app was re- 
     // opened. 
    } 

    public void onPause() 
    { 
     // This method is called each time your activity is about to loss focus. 
     // either since you moved to another activity or since the entire app goes to the 
     // background. 
    } 

} 

底線:總是假設相同的活動可以再次重新運行。

+0

您能否給我舉個例子:「正確的做法是使用其他一些狀態回調,例如onPause/Resume來分配/處理活動使用的資源。」 – LMK

+0

當然,請看一下答案。只是做了一些改變。 –

0

實際上,該特定的應用程序沒有正確關閉。它只是應用程序錯誤。

+0

你能告訴我如何正確關閉應用程序嗎? – LMK

+0

您必須從退出按鈕或返回按鈕關閉應用程序。然後只有該應用程序正確關閉。您可以在任務管理器中檢查應用程序是否仍在運行。 –

相關問題