我有一个应用程序在模拟器和手机中运行良好,但如果我们通过单击手机的退出按钮(而不是从应用程序)关闭应用程序。几个小时后我们重新打开应用程序,它从应用程序中间打开(而不是从第一个屏幕)。使用该应用程序一段时间后,它会被挂起并显示消息'不幸的是,应用程序已停止'。这是移动问题还是应用程序问题。如果应用程序未关闭(在后台运行),是否会导致应用程序崩溃?
回答
我建议您阅读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