views:

207

answers:

3

I've implemented a service that does an asynchronous sync between my application and google docs. I want to update the top level activity of my application when the sync is complete. However because of the service it's possible that the app could be be in a unknown state. Is there a way to make the top level activity, whatever that may be, recreate itself from an asynchtask in a service.

+2  A: 

In your Service, just call startActivity(new Intent(this, TopLevelActivity.class)). This will launch your TopLevelActivity if it's not already running, or call your TopLevelActivity's onNewIntent() method if it is already running, and bring it to the top. You can override onNewIntent() and capture the Intent if you want to be notified.

synic
Bear in mind that users do not necessarily appreciate an activity popping up out of nowhere in the middle of what they are doing (e.g., playing a game, typing a text message, using the dialpad in a phone call).
CommonsWare
Thanks synic. This works! however I did have to add a static flag to my activity classes which tells me if they are currently active. I flip this flag in pause and resume. This way I don't change the state of the phone. I just update the UI if the activity is open. I did override onNewIntent() where I check for a boolean which is added to the intent my service sends. That way if the intent came from my service i update the ui. I'm not extremely please with this approach because of the booleans but it functions. Thanks again.
Dave.B
Alternatively, you could have your Activity register with the service, using some custom methods that you add to your service, in `onResume()`; something like `mService.registerActivity(this)`, and `mService.unregisterActivity(this)` in `onPause()`, that way the Service knows if the Activity is currently active.
synic
+2  A: 

The correct way to do this, I believe, is to use a Remote Interface using AIDL: http://developer.android.com/intl/zh-CN/guide/developing/tools/aidl.html

You make a simple *.aidl file with the interface in it, and the Android tools will generate the Interface class for you. It will allow you to register Callback methods. Much cleaner than tossing startActivity intents back and forth.

BenTobin
Thanks Ben. I'll look into this.
Dave.B
+2  A: 

You should broadcast an Intent from the service and then have the Activity be a broadcast receiver.

Here is a write up on BroadcastReceiver.

Hope this helps.

Brian ONeil
I read that broadcasting shouldn't be done while communicating inside your application because of the overhead. I think Ben Tobin's solution is likely the best answer.
Dave.B