Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent screen rotation on Android

I have one of my activities which I would like to prevent from rotating because I'm starting an AsyncTask, and screen rotation makes it restart.

Is there a way to tell this activity "DO NOT ROTATE the screen even if the user is shaking his phone like mad"?

like image 771
Sephy Avatar asked Apr 28 '10 15:04

Sephy


People also ask

How do I restrict orientation on Android?

Add android:screenOrientation="portrait" to the activity you want to disable landscape mode in.

Can you disable screen auto rotation?

Method two: Disable Auto-rotate from Display Settings Right-click the Desktop, then select Display settings. Under Display, switch Lock rotation of the display to off to lock the auto-rotation.


2 Answers

Add

android:screenOrientation="portrait"  

or

 android:screenOrientation="landscape"  

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

like image 59
lbedogni Avatar answered Sep 23 '22 14:09

lbedogni


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.

like image 40
Emre Yazici Avatar answered Sep 23 '22 14:09

Emre Yazici