Run code only once after an application is installed on Android device
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.
- Check if boolean X is True in shared preferences
- 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();
}
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>
use this simple code
if (getPreferences(MODE_PRIVATE).getBoolean("is_first_run", true)) {
/*
* your code here
*/
getPreferences(MODE_PRIVATE).edit().putBoolean("is_first_run", false).commit();
}
Use a boolean value to check if its first execution of code or not.
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedpreferences.edit();
if(sharedpreferences.getBoolean("is_first_exec",false))
{
editor.putBoolean("is_first_exec",false);
//your code here ...
}
The getBoolean()
like every other get method of SharedPreference, takes a second default parameter which will return null the first time (as there is nothing in the SharedPreference file). Thus, the code inside the if(){...}
block will execute only once.
Footnotes: SharedPreferences
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// Initialize SharedPreferences
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// Create a new boolean and preference and set it to true
boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
// If the activity has never started before...
if (isFirstStart) {
// Launch app intro
final Intent i = new Intent(MainActivity.this, DefaultIntro.class);
runOnUiThread(new Runnable() {
@Override public void run() {
startActivity(i);
}
});
// Make a new preferences editor
SharedPreferences.Editor e = getPrefs.edit();
// Edit preference to make it false because we don't want this to run again
e.putBoolean("firstStart", false);
// Apply changes
e.apply();
}
}
});
// Start the thread
t.start();
精彩评论