简体   繁体   中英

A better way to prohibit activity rotation to portrait mode after screen is locked?

It is one of Android's idiocies that after the screen is locked while an app/activity is in landscape mode, it will be destroyed and re-created although the user will often keep the device in the same position and will unlock it a short time later. In this case, after unlocking the screen again, the activity (which was put to portrait mode by Android) will be destroyed and recreated in landscape mode again. This is why the user experience is annoying in landscape mode. Why was this decision made? If the user has changed the device orientation, it would be enough to react to this change after unlocking.

And concerning resources this is a bad idea, too. For example, in a camera app, I don't want the camera to be initialized anew as long as the screen is locked. This is a good practice for any UI, too.

My current solution looks like this:

public class CameraActivity extends Activity {

    private boolean screenWasLocked;

    public boolean isScreenLocked() {

        KeyguardManager myKM = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
        return myKM.inKeyguardRestrictedInputMode();
    }

    protected void create() {

        setContentView(R.layout.activity_main);

        // ...
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        if (isScreenLocked()) return;


        create();
    }

    @Override
    protected void onResume() {

        super.onResume();


        if (isScreenLocked()) {

            screenWasLocked = true;
            return;
        }
        else if (screenWasLocked) {

            screenWasLocked = false;
            create();
        }


        // ...
    }

    // Things you do here must accept that logic in create()/onResume() probably wasn't executed
    @Override
    protected void onPause() {

        // ...

        super.onPause();
    }
}

Can you suggest me a better one?

this use.

<activity android:name="variables.App.Splash"
              android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode"
              android:screenOrientation="portrait">

and add to activity

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    super.onWindowFocusChanged(hasFocus);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM