Application Launch Count
Solution 1:
This is actually quite simple. Using SharedPreference or the Database.
during OnCreate add 1 to the numberofTimes counter and commit.
OnCreate (Bundle bundle){
mPref = getPreferences();
int c = mPref.getInt("numRun",0);
c++;
mPref.edit().putInt("numRun",c).commit();
//do other stuff...
}
OnCreate is called regardless of you start the app or you resume the app, but isFinishing() returns true if and only iff the user (or you) called finish() on the app (and it was not being destroyed by the manager)
This way you only increment when you are doing fresh start.
the isFinishing() Method inside of a OnPause method to check to see if the activity is being finish() or just being paused.
@Override
protected void OnPause(){
if(!isFinishing()){
c = mPref.getInt("numRun",0);
c--;
mPref.edit().putInt("numRun",c).commit();
}
//Other pause stuff.
}
This covers all your scenarios:
1. user starts app/activity (+1)-> finishes app, exit with finish()
2. user starts app (+1) -> pause (-1) -> returns (+1)-> finish
3. user starts app (+1) -> pause (-1) -> android kills process (0) -> user returns to app (+1) -> user finish.
every scenario you only increment the "times run" counter once per "run" of the activity
Solution 2:
Just:
-
declare:
private SharedPreferences prefs; private SharedPreferences.Editor editor; private int totalCount;
-
initialize in
onCreate()
:prefs = getPreferences(Context.MODE_PRIVATE); editor = prefs.edit();
-
print or count wherever you want (any where in
onCreate()
or any specific click as you specified):totalCount = prefs.getInt("counter", 0); totalCount++; editor.putInt("counter", totalCount); editor.commit();
-
now print
totalCount
where you want to count e.g.:System.out.println("Total Application counter Reach to :"+totalCount);