Question

Hi and thanks for your help.

I have the following situation.

My Activity is bound to a Service that performs heavy data retrival from internet via an AsyncTask.

Since the Service is heavy I need to make make sure it is stopped when the user navigates away for the Activity, therefore I make sure to stop the service in onDestroy().

When configuration changes onDestroy() is called - and so are onPause() and onStop()- and subsequently the Service is stopped by onDestroy().

The point is that I do not want the Service tho stop on configuration change.

Please any suggestion very much appreciated!

And thanks for your help!

Was it helpful?

Solution

You can call isChangingConfigurations() in onDestroy() on API Level 11 and above. You can refer to this post, How to distinguish if activity is changing configurations.

Maybe you should take another approach. I think you should use a IntentService (which runs in background, no more need for AsyncTask), use that service to retrieve & store data, and then notify the Activities that the data is updated, using a Broadcast maybe.

OTHER TIPS

I can suggest two things for your issue.

1) use below tag in your activity(Yes Activity not service) declaration in Manifest file, which will basically avoid recreation of Activity on orientation change. hence onDestroy will not be called.

android:configChanges="keyboardHidden|orientation"

2) you can kill/stop your service on below method in your activity, which in terms will only be called when User want to navigate away from your activity. and You should also stop your service whenever you are starting another activity or so.

 @Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
}

Try with this :

<service android:name=".yourService"
       android:configChanges="keyboardHidden|orientation"></service>

Apply this attribute to your manifest file.

Short Explanation :

By default, when certain key configuration changes happen on Android (a common example is an orientation change), Android fully restarts the running Activity/Service to help it adjust to such changes.

When you define android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Please don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself. Yes, I know what I'm doing".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top