Skip to content Skip to sidebar Skip to footer

Threads And Device Orientation

I got main Activity that on button press starts other class named Getter and that Getter class creates 1-60 000 threads (which do network stuff), so it takes some time until they a

Solution 1:

Our way of handling this is to start the async task from a sticky app.Service and allow the async task to communicate with the parent Service which in turn communicates with anyone listening to it's broadcast events via the BroadcastReceiver framework. I have gone someway to describe this mechanism here.

On orientation change, your app.Activity will be destroyed but the background Service won't be (it can be onLowMemory & a myriad of other circumstances but it probably won't). On recreating the activity you can check to see if your service is still running via the solution I posted here. Based on that result you can decide what to do with the UI, redisplay/re-add the progress dialogue or whatever and re-register your receiver to listen for events coming out of the Service.

The responsibilities between these layers works like this;

  1. AsyncTask
    • Does the work.
    • Reports back what it's up to and when it's done by firing events (Intents)
    • That's it
  2. Service
    • Hosts an orientation unaware container for the AsyncTask
    • Registers listeners for events emanating from the AsyncTask in #onCreate
    • Executes the AsyncTask in #onStartCommand
    • Stops itself (see stopSelf()) when it receives the "I have finished" event from the AsyncTask
    • Fires events describing progress to anyone listening
  3. Activity
    • Starts the Service which in turn starts the AsyncTask.
    • Registers listeners for events emanating from the Service in #onCreate
    • Checks whether a Service is running already during onCreate to make a decision as to whether work is ongoing or needs starting.

3 elements with discrete unconfused roles. That's the way we like it. The only nuance with this approach is the use of the BroadcastReceivers. If you are comfortable with those then you are golden.

Solution 2:

You can Lock Orientation

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

Refer https://stackoverflow.com/a/3611554/1008278

Post a Comment for "Threads And Device Orientation"