2013-10-22 30 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

您必须从退出按钮或返回按钮关闭应用程序。然后只有该应用程序正确关闭。您可以在任务管理器中检查应用程序是否仍在运行。 –

相关问题