我有一个应用程序在模拟器和移动设备上运行良好但是如果我们通过单击电话的退出按钮(而不是从应用程序)关闭应用程序。几个小时后我们重新打开应用程序,它从中间打开应用程序(不是从第一个屏幕)。并在使用该应用程序后,有时会被挂起并显示消息“不幸的是app已经停止”。这是移动问题还是应用程序问题。
答案 0 :(得分:1)
我建议您阅读Activity文档。 Android OS有自己的应用程序生命周期管理。 每个活动都保持“活动”,直到调用onDestroy。例如,操作系统可以将活动保持活动几个小时,然后在没有足够的内存来执行其他任务时将其杀死。
在你的情况下发生的情况很可能是当你再次打开app时(在模拟器中活动可能已经被杀死)重新运行相同的活动并且你处于一个糟糕的状态,因为可能有些对象是处置或重新初始化。
正确的做法是使用一些其他状态回调,例如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.
}
}
底线:始终假设相同的活动可以重新运行。
答案 1 :(得分:0)
实际上,该特定应用程序未正确关闭。它只是应用程序错误。