Android: count number of app launches
I need to count the number of times the user launches an app. I'm storing the value in a shared preference, and putting the count logic inside 开发者_JS百科onCreate()
.
Now, since onCreate()
is called in a number of different scenarios, not all of which include the user actually launching the application, I'm using the saved instance state bundle to store a flag set in OnSaveInstanceState()
-- if the flag is absent, I consider the user started the app manually.
Is this necessary, or is just checking for a null
bundle passed to onCreate()
enough? In either case, why?
You could call getCategories()
on the intent to see if it includes the LAUNCHER catagory.
You could think about this another way... increment the counter every time onDestroy() is called. This way you would be guaranteed that the program is actually out of memory, and the counter will only ever be off by 1 at most.
Just throwing an idea out there, hope it gives you some more of your own!
A null
check in onCreate()
should work just fine. No need to set a separate flag in onSaveInstanceState()
. There is one possible issue though.
Say the user put your application in background (by pressing home key). The application process will eventually get killed. When the user restarts the application, you will receive a proper Bundle
object in onCreate()
with the flag set. The user can prevent your counter from being incremented by simply backgrounding your application everytime.
If backgrounding could be an issue, you might try something like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (getLastNonConfigurationInstance() == null) {
counter++;
}
}
public Object onRetainNonConfigurationInstance() {
return new Object();
}
I have used the above code before and it works on Eclair, FroYo and Gingerbread. It seems getLastNonConfigurationInstance()
and onRetainNonConfigurationInstance()
have been marked deprecated in Honeycomb, so I am not sure how it will work in case you are targeting Honeycomb.
Inside the onCreate
method, include a check to Activity#getCallingActivity
. It returns null
if the app was not started from another activity.
First off, thank you all for your answers. They all helped some way or another.
That said, after several tries and different approaches, I think there is no actual 100% reliable way of determining when the user has launched the app. None of the activity life-cycle callbacks can really be used tackle the issue, neither individually nor combined.
The closest I got was counting the number of onResume()
calls, and then substracting from it in onPause()
depending on the return of isFinishing()
. This approach, however, doesn't account for the home button, among maybe other things a user can do to hide apps.
I will update this answer if I ever find a way to do this reliably.
精彩评论