I tried to implement the following code to handle screen orientation changes.
****DataBaseUpdateService.java****
public class DataBaseUpdateService extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Updatetask Task = new Updatetask(this.getApplicationContext());
if(Task.getStatus() == AsyncTask.Status.PENDING){
Task.execute();};
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
}
==========================================================================
****Androidmanifest.xml****
<activity
android:name=".DataBaseUpdateService"
android:configChanges="keyboardHidden|orientation"/>
Those codes work perfectly with android 3.x or lower. However, it does not work properly for android 4.x.
Do you have any idea what the problem is??
I'm not 100% sure that this will work, but you could try save your AsyncTask with onNonConfigurationChangedInstance().
Solution 1 – Think twice if you really need an AsyncTask. Solution 2 – Put the AsyncTask in a Fragment. Solution 3 – Lock the screen orientation Solution 4 – Prevent the Activity from being recreated.
Reference:http://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/
..... the problem happens because the activity recreated when configuration changes,like orientation change etc. You can lock the orientation change in the onPreExecuted() method of asyntask and unlock it in the onPostExecuted() method.
Add
screenSize
value as well.From documentation:
So, manifest should look like this (if you want to handle orientation changes yourself):