Reputation: 363
I am using a broadcastreceiver to listen for an intentservice which is set off via an onclick method. This is all fine but if the screen is rotated, I have had to put an unregister in the onPause (I have also tried this in onDestory) method and then in the onResume I re-register the broadcastreceiver.
My problem is, during the time of the broadcastreceiver being unregistered/registered the intentservice can send its broadcast back to say its done and then this means that the broadcastreceiver is still sitting there waiting for something that has already happened.
I have tried to use a sleep in the intentservice before the broadcast but this is by no means full proof as if the device is rotated again there is a timing issue.
I start and register the intent service and broadcastreceiver from the onClick as follows :
Intent intentMyIntentService = new Intent(myclass.this,myservice.class);
startService(intentMyIntentService);
mybroadcastreciver = new br();
IntentFilter intentFilter = new IntentFilter(myservice.ACTION_ServiceE);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(mybroadcastreciver, intentFilter);
I the br method is the broadcastreceiver which as its onReceive method and I handle the configuration change with the onSaveInstanceState method and then check in the onCreate to see if the Bundle != null to then retrieve the Boolean which are set depending whether the intentservice is complete using the broadcast that it sends to the receiver.
This does all work if the screen is not rotated. However I know there are other ways to handle screen rotation but I am writing an app to work from API 8 to 17 .
Thanks
Tim
Upvotes: 0
Views: 1070
Reputation: 895
One way is to maintain the same BroadcastReceiver
object across screen orientation change:
1) Return the BroadcastReceiver
object in Activity.onRetainNonConfigurationInstance()
.
2) Fetch it in Activity.onCreate()
using (BroadCastReceiver) getLastNonConfigurationInstance()
. It returns null
if not saved.
3) In onClick()
, only create the BroadcastReceiver
object if it's not obtained in Activity.onCreate()
.
Upvotes: 0