Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle screen orientation changes when there is an asyntask running with android 4.x

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??

like image 648
Eric Avatar asked Jul 24 '12 12:07

Eric


People also ask

How do you handle a dysfunction in screen orientation android?

If you want to manually handle orientation changes in your app you must declare the "orientation" , "screenSize" , and "screenLayout" values in the android:configChanges attributes. You can declare multiple configuration values in the attribute by separating them with a pipe | character.

How can we cope with screen orientation changes?

Another most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.

What ll happen when rotate the screen while async task running in background?

Solution 1 Rotation of the screen will cause the current Activity to be destroyed and new one recreated. If an AsyncTask is running when this happens, it could give rise to two consequences: 1.


1 Answers

Add screenSize value as well.

From documentation:

Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the screenSize configuration, because it also changes when a device switches between portrait and landscape orientations.

So, manifest should look like this (if you want to handle orientation changes yourself):

****Androidmanifest.xml****
 <activity 
  android:name=".DataBaseUpdateService"
  android:configChanges="keyboardHidden|orientation|screenSize"/>
like image 86
StenaviN Avatar answered Sep 23 '22 04:09

StenaviN