6

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?

Rameez Hussain
  • 6,414
  • 10
  • 56
  • 85
  • there is a small SharedPreference's example is available , just search it and try it. – Lucifer Aug 23 '12 at 13:46
  • 1
    You mean per device for all devices combined? – DeeV Aug 23 '12 at 13:47
  • I know this is way late - but I have come up with a nearly fool-proof answer if you are still looking for the best way tot do this. http://stackoverflow.com/a/22228198/763080 – Phil Mar 06 '14 at 15:03

8 Answers8

9

The problem with using onCreate in an Activity is that this will increment the counter even on orientation changes. Using onCreate in an Application also has a downside in that your counter will only be incremented when after the VM has closed - so even if the app exits and reopens this will not necessarily increment.

The truth is there is no fool-proof method for handling this sort of count, however I have come up with a very good way of doing this, that is about as close to 100% accurate as possible. It requires work in both an Application class and your main Activity class, and relies on timestamps to differentiate between orientation changes and actual app launches. To start, add the following Application class:

/**
 * Application class used for correctly counting the number of times an app has been opened.
 * @author Phil Brown
 * @see <a href="http://stackoverflow.com/a/22228198/763080">Stack Overflow</a>
 *
 */
public class CounterApplication extends Application
{
    private long lastConfigChange;

    /** @param buffer the number of milliseconds required after an orientation change to still be considered the same event*/
    public boolean wasLastConfigChangeRecent(int buffer)
    {
        return (new Date().getTime() - lastConfigChange <= buffer);
    }

    @Override
    public void onCreate()
    {
        lastConfigChange = new Date().getTime();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        lastConfigChange = new Date().getTime();
    }
}

You should add this Application to your AndroidManifest.xml by specifying the name application attribute:

android:name="path.to.CounterApplication"

Now, in your main Activity, add the following in onCreate:

//note that you can use getPreferences(MODE_PRIVATE), but this is easier to use from Fragments.
SharedPreferences prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);

int appOpenedCount = prefs.getInt("app_opened_count", 1);
if (!((CounterApplication) getApplication()).wasLastConfigChangeRecent(10000))//within 10 seconds - a huge buffer
{
    appOpenedCount += 1;
    prefs.edit().putInt("app_opened_count", appOpenedCount).commit();
}

//now say you want to do something every 10th time they open the app:
boolean shouldDoThing = (appOpenedCount % 10 == 0);
if (shouldDoThing)
{
    doThing();
    appOpenedCount += 1;
    //this ensures that the thing does not happen again on an orientation change.
    prefs.edit().putInt("app_opened_count", appOpenedCount).commit();
}
Phil
  • 35,852
  • 23
  • 123
  • 164
9

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 eg.:

     System.out.println("Total Application counter Reach to :"+totalCount);
flotothemoon
  • 1,882
  • 2
  • 20
  • 37
Nirav Mehta
  • 1,715
  • 4
  • 23
  • 42
6

In your Application or Activity's onCreate() method, increment a counter stored in persistent storage such as SharedPreferences.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • 3
    Counting in Activity's `onCreate()` is inproper. If you want to count in Activity though, you should use `onResume()`, not `onCreate()` – Marcin Orlowski Aug 23 '12 at 14:05
  • 3
    not really, since onResume will be called when back is pressed from the next activity (which probably is not wanted). anyway, the notion of application being opened does no make much sense. – njzk2 Aug 23 '12 at 14:13
  • Unless you specify `configchanges:orientation` in your manifest (HIGHLY frowned upon), this will also increment your counter every time the device is rotated! You can get around this using an Application and an Activity, as described in my new response: http://stackoverflow.com/a/22228198/763080 – Phil Mar 06 '14 at 15:09
  • just put it in a if(savedInstanceSate == null){} bloc and you don't get the orientation changes. – UhrArt Jan 13 '16 at 16:48
4

You can use shared preferences. Every time the app is opened, retrieve the preferences, increment the count, then store it right away. The only issue is that if a user deletes the app along with all preferences, then the count will be erased too. Here is an example of committing to the preferences. Use getPreferences to retrieve them at the startup of the app.

SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putString("pref 1", "some text");

editor.commit();
Kcvin
  • 5,073
  • 2
  • 32
  • 54
2

One way:

Keep a property in preferences and on launching activity update preference count by '1', but you may not be able to see this increased value because it stays on phone.

Otherway

Call a service to your server (if you have any) to increment the visit count.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • 1
    "`on launching activity`" ... maybe not very reliable e.g the count may be increased when orientation is changed. – vikki Aug 23 '12 at 13:52
  • @vikki that's exactly true. My new answer solves this problem. http://stackoverflow.com/a/22228198/763080 – Phil Mar 06 '14 at 15:06
2

1. For a simple approach, keep a text file where you increment the value by 1, after reading it. Keep the count increment on OnCreate() method of Activity

2. You can use SharedPreference.

3. Well DataBase can also be used...but i think that too over-kill for this....

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • As I stated above, cunting in Activity's onCreate() is inproper. If you want to count in Activity though, you should use onResume(), not onCreate() – Marcin Orlowski Aug 23 '12 at 14:07
  • @WebnetMobile.com I see why you would want to count in `onResume` but it has its downsides aswell. Implementing this feature would need one to consider orientation changes, device sleep/wake, interruptions by other apps such as a phone call etc. There is no simple answer to this question, it all depends on what OP considers to be a count. – vikki Aug 23 '12 at 15:22
  • #1 text file is abolutily an overkill. you need write permissions and outputstreams. #2 is the way to go – UhrArt Jan 13 '16 at 16:46
0
  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 onFinishing() 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(!onFinishing()){
    c = mPref.getInt("numRun",0);
    c--;
    mPref.edit().putInt("numRun",c).commit();
  }
  //Other pause stuff.
}
Mourice
  • 597
  • 1
  • 5
  • 17
0

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.


Community
  • 1
  • 1