Problem
You have an application that collects app usage data anonymously, so you are obligated to make users aware of this the first time they run your application.
Solution
Use shared preferences as persistent storage to store a value, which gets updated only once. Each time the application launches, it will check for this value in the preferences. If the value has been set (is available), it is not the first run of the application; otherwise it is the first run.
Discussion
You can manage the application life cycle by using the Application class of the Android framework. We will use shared preferences as persistent storage to store the first-run value.
We will store a Boolean flag in the preferences if this is the first run. When the application is installed and used for the first time, there are no preferences available for it. They will be created for us. In that case the flag will return a value of true. After getting the true flag, we can update this flag with a value of false as we no longer need it to be true. See Example 1.
Example 1. First-run preferences
public class MyApp extends Application {
SharedPreferences mPrefs;
@Override
public void onCreate() {
super.onCreate();
Context mContext = this.getApplicationContext();
// 0 = mode private. Only this app can read these preferences.
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
// Your app initialization code goes here
}
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
}
This flag from the preferences will be tested in the launcher Activity, as shown in Example 2.
Example 2. Checking whether this is the first run of this app
if(((MyApp) getApplication()).getFirstRun()) {
// This is the first run
((MyApp) getApplication()).setRunned();
// Your code for the first run goes here
}
else {
// This is not the first run on this device
}
Even if you publish updates for the app and the user installs the updates, these preferences will not be modified; therefore, the code will work for only the first run after installation. Subsequent updates to the app will not bring the code into the picture, unless the user has manually uninstalled and reinstalled the app.
Note
You could use a similar technique for distributing shareware versions of an Android app (i.e., limit the number of trials of the application). In this case, you would use an integer count value in the preferences to indicate the number of trials. Each trial would update the preferences. After the desired value is reached, you would block the usage of the application until the user pays the usage fee.