2016-11-17 17:06
我們知道,系統提供了Android:configChanges="orientation" 清單檔案屬性以監聽螢幕旋轉,進而觸發onConfigurationChanged方法。
但這有時不能完全滿足我們的需求。比如典型的應用場景:視訊播放器的螢幕方向鎖功能。
下面貢獻螢幕旋轉完全控制類ActivityRotationController,解決一切螢幕旋轉問題。
[java] view plain copy
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.pm.ActivityInfo;
- import android.provider.Settings;
- import android.provider.Settings.SettingNotFoundException;
- import android.view.OrientationEventListener;
- public class ActivityRotationController extends OrientationEventListener {
- private int systemRotation;
- private boolean activityRotation;
- private int activityOrientation;
- private Activity activity;
- public ActivityRotationController(Activity activity) {
- super(activity);
- this.activity = activity;
- activityOrientation = activity.getResources().getConfiguration().orientation;
- try {
- systemRotation = getScreenRotation(activity.getContentResolver());
- } catch (SettingNotFoundException e) {
- e.printStackTrace();
- systemRotation = -1;
- }
- openActivityRotation();
- enable();
- }
- public void openActivityRotation() {
- activityRotation = true;
- }
- public void closeActivityRotation() {
- activityRotation = false;
- }
- public boolean isActivityRotationEnabled() {
- return activityRotation;
- }
- public int getActivityOrientation() {
- return activityOrientation;
- }
- @Override
- public void enable() {
- super.enable();
- setScreenRotation(activity.getContentResolver(), 0);
- }
- @Override
- public void disable() {
- super.disable();
- if (systemRotation == -1) {
- return;
- }
- setScreenRotation(activity.getContentResolver(), systemRotation);
- }
- @Override
- public void onOrientationChanged(int orientation) {
- if (orientation < 0) {
- return;
- }
- int newOrientation= ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
- if (orientation >= 0 && orientation <= 60) {
- newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
- }else if (orientation >60 && orientation <120) {
- newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
- }else if (orientation >=120 && orientation <=240) {
- newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
- }else if (orientation >240 && orientation <300) {
- newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
- }else if (orientation >=300 && orientation <=360) {
- newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
- }else{
- return;
- }
- if ((newOrientation != orientation) && activityRotation) {
- activity.setRequestedOrientation(newOrientation);
- activityOrientation = newOrientation;
- }
- }
- private void setScreenRotation(ContentResolver cr, int rotation) {
- Settings.System.putInt(cr, Settings.System.ACCELEROMETER_ROTATION,
- rotation);
- }
- private int getScreenRotation(ContentResolver cr)
- throws SettingNotFoundException {
- return Settings.System.getInt(cr,
- Settings.System.ACCELEROMETER_ROTATION);
- }
- }
作者:薄荷記賬 (轉載請注明原作者)