下一个解决方法可能会帮助您解决问题。
您必须使用代码中的活动扩展所有活动。每当调用 onPause / onResume 方法时,它都会负责设置和恢复正确的方向。
该解决方法适用于清单活动标记中定义的任何类型的方向。
出于我自己的目的,我从ComponentActivity扩展了此类,因此您可能希望将其更改为从Activity、ActivityCompat或您在代码中使用的任何类型的活动中扩展。
public abstract class AbsBaseActivity extends ComponentActivity
{
private int currentActivityOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
private int parentActivityOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
@CallSuper
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.cacheOrientations();
}
private void cacheOrientations()
{
if (this.currentActivityOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
{
final Intent parentIntent = this.getParentActivityIntent();
if (parentIntent != null)
{
final ComponentName parentComponentName = parentIntent.getComponent();
if (parentComponentName != null)
{
this.currentActivityOrientation = this.getConfiguredOrientation(this.getComponentName());
this.parentActivityOrientation = this.getConfiguredOrientation(parentComponentName);
}
}
}
}
private int getConfiguredOrientation(@NonNull final ComponentName source)
{
try
{
final PackageManager packageManager = this.getPackageManager();
final ActivityInfo activityInfo = packageManager.getActivityInfo(source, 0);
return activityInfo.screenOrientation;
}
catch (PackageManager.NameNotFoundException e)
{
e.printStackTrace();
}
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
@CallSuper
@Override
protected void onPause()
{
if (this.parentActivityOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
{
this.setRequestedOrientation(this.parentActivityOrientation);
}
super.onPause();
}
@CallSuper
@Override
protected void onResume()
{
super.onResume();
if (this.currentActivityOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
{
this.setRequestedOrientation(this.currentActivityOrientation);
}
}
}