0

我有一个应用程序在模拟器和移动设备上运行良好,但是如果我们通过单击手机的退出按钮(不是从应用程序)关闭应用程序。几个小时后我们重新打开应用程序,它会从应用程序中间打开(不是从第一个屏幕)。在使用该应用程序几次后,它会被挂起并显示消息“不幸的是应用程序已停止”。这是手机问题还是应用问题。

4

2 回答 2

1

我建议阅读活动文档。Android 操作系统有自己的应用程序生命周期管理。每个活动都保持“活动”,直到调用其 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.
     }

}

底线:总是假设相同的活动可以再次重新运行。

于 2013-10-22T06:39:58.253 回答
0

实际上,该特定应用程序未正确关闭。这只是应用程序错误。

于 2013-10-22T06:37:44.430 回答