Counting how many times my Android app has been opened

后端 未结 8 1221
遇见更好的自我
遇见更好的自我 2020-12-18 07:22

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?

相关标签:
8条回答
  • 2020-12-18 07:56

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

    0 讨论(0)
  • 2020-12-18 08:02

    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.


    0 讨论(0)
提交回复
热议问题