我的应用程序在横向模式下运行。当我的手机进入睡眠状态时,然后onDestroy()然后onCreate()自动调用。我已经声明了android:configChanges =" orientation"和android:screenOrientation =" landscape"。请告诉我该怎么做,以避免这个问题。 我还附上了下面的xml文件。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="m.example.ghb1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="m.example.ghb1.MainActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:configChanges="orientation" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PlayActivity"
android:configChanges="orientation"
android:screenOrientation="landscape"
>
</activity>
</application>
</manifest>
答案 0 :(得分:0)
当我的手机进入睡眠状态时,会自动调用onDestroy()然后onCreate()。
android可以随时调用onDestroy(破坏你的应用和活动),你需要为这种情况准备你的应用程序 - 这里有好文章:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
我已经宣布了android:configChanges =&#34; orientation&#34;和android:screenOrientation =&#34; landscape&#34;。
这是防止android重新创建活动的常见黑客,使用它的程序员经常忘记系统可能在许多其他情况下破坏活动
答案 1 :(得分:0)
Android可以在需要为其他任务释放内存时调用onDestroy()
。您可以做的是覆盖onSaveInstanceState(Bundle savedInstanceState)
并将要更改的应用程序状态值写入Bundle参数,如下所示:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("isRequired", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("myInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
Bundle本质上是一种存储NVP(“名称 - 值对”)映射的方式,它将被传递到onCreate和onRestoreInstanceState,你可以在这里提取这样的值:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}