Java how to stop screen rotation in android code

www‮‬.lautturi.com
Java how to stop screen rotation in android code

To prevent the screen from rotating in Android, you can use the setRequestedOrientation method of the Activity class to specify the orientation that the activity should be in.

Here's an example of how you can do this in your activity's onCreate method:

public class MyActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

This code will set the orientation of the activity to portrait mode, so the screen will not rotate even if the device is rotated.

You can also specify other orientation modes such as ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to lock the screen in landscape mode, or ActivityInfo.SCREEN_ORIENTATION_USER to allow the user to control the screen orientation.

Note that the setRequestedOrientation method will not work if the device's display settings are set to "Auto-rotate". In this case, you can use the setOrientation method of the WindowManager class to manually set the screen orientation.

Here's an example of how you can do this:

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
    wm.setOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

This code will set the screen orientation to portrait mode regardless of the device's display settings.

Note that using the setOrientation method may cause the activity to be recreated, so you should use it sparingly and only when necessary.

Created Time:2017-11-03 23:27:12  Author:lautturi