Prevent screen rotation on Android
You can follow the logic below to prevent auto rotate screen while your AsyncTask
is running:
- Store your current screen orientation inside your activity using
getRequestedOrientation()
. - Disable auto screen orientation using
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR)
. - Run/execute your
AsyncTask
. - At the end of your
AsyncTask
restore your previous orientation status usingsetRequestedOrientation(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.
Add
android:screenOrientation="portrait"
or
android:screenOrientation="landscape"
to the <activity>
element/s in
the manifest and you're done.
The easiest way I found to do this was to put
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
within onCreate, just after
setContentView(R.layout.activity_main);
so...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}