我有一個應用程序在模擬器和手機中運行良好,但如果我們通過單擊手機的退出按鈕(而不是從應用程序)關閉應用程序。幾個小時後我們重新打開應用程序,它從應用程序中間打開(而不是從第一個屏幕)。使用該應用程序一段時間後,它會被掛起並顯示消息'不幸的是,應用程序已停止'。這是移動問題還是應用程序問題。如果應用程序未關閉(在後臺運行),是否會導致應用程序崩潰?
回答
我建議您閱讀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.
}
}
底線:總是假設相同的活動可以再次重新運行。
您能否給我舉個例子:「正確的做法是使用其他一些狀態回調,例如onPause/Resume來分配/處理活動使用的資源。」 – LMK
當然,請看一下答案。只是做了一些改變。 –
實際上,該特定的應用程序沒有正確關閉。它只是應用程序錯誤。
你能告訴我如何正確關閉應用程序嗎? – LMK
您必須從退出按鈕或返回按鈕關閉應用程序。然後只有該應用程序正確關閉。您可以在任務管理器中檢查應用程序是否仍在運行。 –
- 1. 如果FileInputStream未關閉,應用程序是否會崩潰?
- 2. 前臺iPhone應用程序導致我的後臺應用程序崩潰
- 3. 第二次運行線程會導致應用程序崩潰
- 4. ObjectAtIndex會導致應用程序崩潰
- 5. JpcapWriter會導致應用程序崩潰
- 6. 應用程序崩潰是在後臺
- 7. 後臺線程導致應用程序崩潰後無錯誤
- 8. 我的應用程序關閉後應用程序崩潰
- 9. iOS:如果應用程序未在後臺運行,則在啓動時調用openURL崩潰應用程序
- 10. WIX在未能關閉導致應用程序崩潰的應用程序後繼續卸載
- 11. 應用程序在運行線程關閉時崩潰
- 12. iPhone應用程序崩潰,而應用程序運行在後臺模式
- 13. 應用程序在關閉時崩潰(?)?
- 14. Qt應用程序在後臺崩潰
- 15. 如果應用程序崩潰,JUnique鎖定的應用程序不會運行
- 16. 如何運行C#控制檯應用程序(如果崩潰)
- 17. 後臺應用程序的GCM推送通知導致崩潰
- 18. 應用程序在關閉後運行
- 19. httppost導致應用程序崩潰
- 20. Swift casting導致應用程序崩潰
- 21. Firebase AuthUI導致應用程序崩潰
- 22. 圖片導致應用程序崩潰
- 23. UIPickerView導致應用程序崩潰
- 24. onClickListener導致應用程序崩潰
- 25. ScrollView導致應用程序崩潰
- 26. iOS appendFomat導致應用程序崩潰
- 27. requestWindowFeature(Window.FEATURE_NO_TITLE);導致應用程序崩潰?
- 28. AppCompatActivity導致應用程序崩潰
- 29. UIView removeFromSuperview導致應用程序崩潰
- 30. 微調導致應用程序崩潰
請在你的問題中加入代碼 – Darshak
至少你應該發佈貓日誌錯誤日誌.. –
雅是多數民衆贊成真的,但其工作正常在模擬器,有些時候(很少)我在mobile.so這個消息我不能看到logcat。 – LMK