Prevent screen rotation on Android Prevent screen rotation on Android android android

Prevent screen rotation on Android


Add

android:screenOrientation="portrait" 

or

 android:screenOrientation="landscape" 

to the <activity> element/s inthe manifest and you're done.


You can follow the logic below to prevent auto rotate screen while your AsyncTask is running:

  1. Store your current screen orientation inside your activity using getRequestedOrientation().
  2. Disable auto screen orientation using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR).
  3. Run/execute your AsyncTask.
  4. At the end of your AsyncTask restore your previous orientation status using setRequestedOrientation(oldOrientation).

Please note that there are several ways to access Activity (which runs on UI thread) properties inside an AsyncTask. You can implement your AsyncTask as an inner class or you can use message Handler that poke your Activiy class.


In your Manifest file, for each Activity that you want to lock the screen rotation add: if you want to lock it in horizontal mode:

<activity        ...        ...        android:screenOrientation="landscape">

or if you want to lock it in vertical mode:

<activity            ...            ...            android:screenOrientation="portrait">