Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code only once after an application is installed on Android device

Tags:

android

I want to run a piece of code once only after the application is installed. After it has been executed, that particular piece of code should not be called again, even for an upgrade.

like image 403
Zach Avatar asked Aug 15 '11 13:08

Zach


2 Answers

  1. Check if boolean X is True in shared preferences
  2. If not:
    a. Run the special code
    b. Save x as true in shared preferences

For example:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
    // run your one time code
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("firstTime", true);
    editor.commit();
}
like image 123
MByD Avatar answered Nov 16 '22 02:11

MByD


I've used a shared preference in the past, but if you are wanting to do something onInstall you could also look at a install receiver. MyInstallReciever implements BroadcastReciever

<receiver
    android:name="com.MyInstallReciever"
    android:exported="true">
    <intent-filter>
        <action
            android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>
like image 33
scottyab Avatar answered Nov 16 '22 01:11

scottyab