Thursday 19 April 2012

Count How many times your application has run on device

Count howmany time your application has opened on device using shared preference.
put following code in your Main activity.




        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);
        
        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);
        
        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");
        
        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important


YOUR CODE WILL LOOK LIKE FOLLOWING,



package com.AppOpenedCount;


import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;


public class CountAppOpenedActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);
        
        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);
        
        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");
        
        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
        
    
}

2 comments:

Unknown said...

Hi sir,
If once the application is launched,
certainly my application is need to call the onCreate(...),so there is a chance to increase the count,so how can rectify that one ?

Unknown said...
This comment has been removed by the author.