tags:

views:

264

answers:

3

I know Android's Activity model is a bit different from what I usually consider to be an "app".

I want to do something (in this case, check some notifications on a server and show them if available) when my app is "launched". What is a good way to accomplish this?

I likely don't want to do it in an activity's OnCreate, since each activity can be created any number of times - the code would get called more often than necessary.

The app also has multiple entry points - would I have to duplicate the check in each activity?

What I'm thinking of doing is setting up this code inside the Application object, along with a flag that tracks whether it's already been called - and just call it from each Activity's onCreate().

Is there a better or more "proper" way to do this?

A: 

Can you just check if the bundle passed to onCreate() is null?

It's not null "If the activity is being re-initialized after previously being shut down..."

joeforker
A: 

There's probably no harm in putting it in onCreate; the Activity is really only destroyed when the OS needs the RAM for something else, not when the user goes to another app.

EDIT: You can also have a Service that runs when the device gets booted up, too. This might be a better option if you also want to check when the app starts, since you'll only have to call context.startService from the Activity to run the check. Just be sure to stop it when it's done if you don't need it to be persistent.

Jarett
Well, there are some cases, when onDestroy() is called in response to somewhat innocent actions - like hitting the BACK button or changing the device's orientation (unless explicitly specified otherwise). And only in the latter case, the Bundle parameter passed to onCreate() is NOT null.
Dimitar Dimitrov
+4  A: 

The right, Android-approved way to do this is:

  • Create your own android.app.Application class
  • Override the onCreate method
  • In the AndroidManifest.xml, change the android:name attribute of the application element to the name of your class
  • Now, whenever your app is "started" (any one of your activites is started for the first time and no other instances are alive) onCreate will be called.

You may also find the onTerminate method useful.

Isaac Waller
Thanks - that's probably what I need, I'll give it a try.
alex_c
Whoa...I never realized you could do that. Makes sense now that I know, though...
Jarett