Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Launch Count

Tags:

android

I am working on an application, wherein after say 5 times the app is opened by a user, at 6th attempt the app should ask for feedback from user. I tried using Activity OnStart,OnResume, but its not working out since even after leaving and re-entering activity these methods are called. Also as per android functionality, I cannot quit app so that I can find it out from the first activity called. How do I find how many times the app was launched?

I hope this is not confusing.

Edit

Alternatively is there a way, wherein I can always resume my app from the first activity( or welcome page for eg.), once user presses home to quit the app.

like image 635
Tushar Vengurlekar Avatar asked Apr 27 '11 05:04

Tushar Vengurlekar


2 Answers

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

like image 145
Dr.J Avatar answered Oct 14 '22 12:10

Dr.J


Just:

  1. declare:

    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private int totalCount;
    
  2. initialize in onCreate():

    prefs = getPreferences(Context.MODE_PRIVATE);
    editor = prefs.edit();
    
  3. 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();
    
  4. now print totalCount where you want to count e.g.:

     System.out.println("Total Application counter Reach to :"+totalCount);
    
like image 42
Nirav Mehta Avatar answered Oct 14 '22 10:10

Nirav Mehta