android 检测屏幕方向,Android 8.1屏幕方向问题:翻转以横屏纵向屏幕

下一个解决方法可以帮助您解决问题。

您必须使用代码中的一项来扩展所有活动。 每当调用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);

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值