I am developing an android app and I want to know how many times it has been opened. Is there a way to do this?
In your Application or Activity's onCreate()
method, increment a counter stored in persistent storage such as SharedPreferences
.
As I have said in another answer, I think the following is the best solution:
private static boolean valueOfLaunchCountModified = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
if(!valueOfCountModified){
preferences = getPreferences(MODE_PRIVATE);
launchCount= preferences.getInt("launchCount", 0);
if(preferences.edit().putInt("launchCount", ++launchCount).commit()){
valueOfCountModified = true;
}
}
if(launchCount == 5 && valueOfCountModified){
//Do whatever you want
}
}
If we remember the definition of a static variable, we will discover that is perfect for us:
They are associated with the class, rather than with any object. Every instance of the class shares a class variable.
When onPause
method or an orientation change is executed the value of valueOfLaunchCountModified
doesn't change; however, if the app process is destroyed, the value of valueOfLaunchCountModified
changes to false.