【发布时间】:2017-10-21 14:16:04
【问题描述】:
我已设置锁定方向
并添加了带有 2 个简单类的示例代码,如下所示:
SplashLandscapeActivity.java
public class SplashLandscapeActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("start", "xxxx start Activity SplashLandscapeActivity");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashLandscapeActivity.this, TestActivity.class));
finish();
}
}, 500);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("start", "xxxx onDestroy Activity SplashLandscapeActivity");
}
}
TestActivity.java
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("start", "xxxx start Activity TestActivity "
+ getResources().getConfiguration().orientation);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("start", "xxxx onDestroy Activity TestActivity "
+ getResources().getConfiguration().orientation);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".SplashLandscapeActivity"
android:theme="@style/SplashTheme"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".TestActivity"
android:screenOrientation="portrait"/>
</application>
</manifest>
当我使用new Handler().postDelayed (SplashLandscapeActivity.java) 启动TestActivity 时,它启动了两次,第一个具有Landscape 方向,然后切换回portrait。日志显示了一切:
xxxx 启动 Activity SplashLandscapeActivity
xxxx 启动 Activity TestActivity 2 //
xxxx onDestroy Activity TestActivity 1
xxxx 开始 Activity TestActivity 1 //
xxxx onDestroy Activity SplashLandscapeActivity
如果我删除 Handler,TestActivity 现在开始像正常的肖像。
xxxx 启动 Activity SplashLandscapeActivity
xxxx 开始活动 TestActivity 1
xxxx onDestroy Activity SplashLandscapeActivity
所以,我的问题是:
1- 此系统是否存在问题或其预期行为?为什么activity 被重新启动,即使screenOrientation 被设置为固定在Manifest 中?
2- 实际上,我的真实项目没有任何Handler,但与activity 启动两次(在以Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK 启动之后)存在相同的问题。我该如何处理这个问题?
【问题讨论】:
-
您是否尝试过修改清单方向。就像同时保持纵向模式一样
-
什么意思?我用它们来模拟我的问题。无论如何,我的预期是
activity从未启动过两次。 -
如果处理程序被删除并且您在设备处于锁定纵向时启动了应用程序,应用程序是否会像在到达
TestActivity之前那样旋转?还是直接纵向跳转到TestActivity而不旋转?我的猜测是,这可能是由于在活动已执行onCreate并且可能onResume执行之后调用了配置更改,并且如果没有发生配置更改,例如跳过SplashLandscapeActivity并直接启动TestActivity它不会被调用,因此它不会重新启动TestActivity。 -
@ahasbini
onConfigurationChanged永远不会在TestActivity上调用,即使它已被系统重新启动(我猜的)。 -
我可以给个提示,你可以从
onCreate方法中检查onSaveInstanceState,第二次活动活动将有一些不同于null的东西。
标签: android screen-orientation activity-lifecycle