Run Code Only Once After an Application Is Installed on Android Device

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

  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();
}

Run a piece of code only once when an application is installed

Before all you can use SQLiteOpenHelper. It is preferred way to do things with database. This class have a onCreate(SQLiteDatabase) method, that called when first creating database. I think it suits you well.

If you want more flexibility and your first time logic is not tied only with database, you can use sample provided earlier. You just need to put it in startup spot.

There are 2 startup spots. If you have only single activity, you can put your code in onCreate method, so it will be like this:

public void onCreate(Bundle savedInstanceState) {
// don't forget to call super method.
super.onCreate(savedInstanceState);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();

// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}

Don't forget to put activity declaration in manifest, as well as it's intentfilters (action = MAIN, category = LAUNCHER).

If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers).

Just create class like that:

public class App extends Application {

@Override
public void onCreate() {
super.onCreate();

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();

// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}

All you need for this to work, is put in application tag in AndroidManifest.xml attribute android:name=".App".

<!-- other xml stuff -->

<application ... android:name=".App">

<!-- yet another stuff like nextline -->
<activity ... />
</application>

Create a function that fires only once after app is installed on phone

I added a field to the localstorage and on startup just check if that field exists. So something like this:

if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}

Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android

Run code once after each boot on Android

I have found a solution to this that seems reliable and meets my requirements. I read the contents of the file /proc/sys/kernel/random/boot_id, which gives a unique boot identifier reset every time the device is rebooted.

By reading this file and comparing the value to one stored in SharedPreferences, I can reliably determine whether the device has been rebooted since the last time I ran my initialisation code, without depending on the device clock. This works in all user profiles as they all have their own SharedPreferences.

The advantage of this approach is that I can check for a change whenever I receive any broadcast and when my app starts, so I can run the initialisation regardless of what happens first and even if the ACTION_BOOT_COMPLETED broadcast is delayed or missed (common on slow devices).

Unfortunately none of the other answers provided a reliable way to do this, but Hardik Chauhan's intent filter priority tip was useful, because I receive ACTION_BOOT_COMPLETED much earlier with that set.

How can I execute something just once per application start?

SharedPreferences seems like ugly solution to me. It's much more neat when you use application constructor for such purposes.

All you need is to use your own Application class, not default one.

public class MyApp extends Application {

public MyApp() {
// this method fires only once per application start.
// getApplicationContext returns null here

Log.i("main", "Constructor fired");
}

@Override
public void onCreate() {
super.onCreate();

// this method fires once as well as constructor
// but also application has context here

Log.i("main", "onCreate fired");
}
}

Then you should register this class as your application class inside AndroidManifest.xml

<application android:label="@string/app_name" android:name=".MyApp"> <------- here
<activity android:name="MyActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

You even can press Back button, so application go to background, and will not waste your processor resources, only memory resource, and then you can launch it again and constructor still not fire since application was not finished yet.

You can clear memory in Task Manager, so all applications will be closed and then relaunch your application to make sure that your initialization code fire again.

Run code only once after a fresh installation,Shared Preference is not a solution please see below description

The answer hinges on what "only once" means.

Once per application install

Set a SharedPreference.

If the user clears data, or uninstalls then reinstalls, the code will be run again.

Once per device

Save a empty file (a flag file) in a well-known location on external storage.

You can either do that:

  • in the application's own storage, which will be cleared at uninstall but not when the user hits Clear Data.
  • in shared external storage.

This second approach is promising: it is resistant to Clear Data and reinstalls.

However, using external storage where the storage is removable, or unmountable is tricky, and I'm not sure what your fallback would be if the storage isn't available. (clue: fail fast).

You also may not trust your users not to (accidentally or deliberately) delete the carefully placed files.

Once per user

I think this is out of scope for this question. But you should start by looking at AccountManager docs, and go from there.

Once per device, seriously this time

Ok, so:

  • we don't want to fail fast if we can't read external storage.
  • we don't want to do belt and braces with the above, because bad actors delete the flag files on external storage, and Clear Data.
  • we must only do once per device ever, even if the device is factory reset and external storage is wiped?

We'll have to check that with an external source which can store the state for this device; let's call that a "server".

We need an identifier to uniquely identify ourselves to the server.

Ordinarily, you would generate a UUID, and store it somewhere. But we can't trust any of our storage options.

So we need to generate an identifier from our static external environment. iPhone's now deprecated UDID was exactly this, generated from various hardware identifiers.

Copying this link would be a great start, but depending on your security clearance you may want to make your own. There may be privacy implications if everyone in the world used your app or the same algorithm as your app (this is why Apple deprecated UDID, and why each app should use its own UUID).

Either way, this is an extremely large amount of engineering effort (including the server) for (at best) an edge case, so I'd avoid it.

Worse, it ties your app to having an internet connection, which depending on your context, may be a bad thing.

Furthermore, a rooted device will have access to change any or all of these identifiers. It gets a bit philosophical after that.

Once per application lifetime

Do it manually. Seriously, do it by hand, either before you deploy, or sometime after.

If you need to pick a winning device, then you need a server and some way of identifying the device, as above. Do it manually, then pick then tell the winner. But that's also out of scope for this Android question.

Execute Android code after installation

I tried below code to make this work change it to suit your needs

SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
if (isFirstRun)
{
// Code to run once
SharedPreferences.Editor editor = wmbPreference.edit();
editor.putBoolean("FIRSTRUN", false);
//editor.commit();
editor.apply();
}

How to run code only when my app is updated

onUpgrade for sqlite simply check if database is present, then what is its version. If Version of current DB is lower then the one in APK it will clear the DB and updated the DB with new one.
Similarly if you clear the application cache. All the file including the DB will be cleared

Similarly you can implement in you application:

like have a static public int version = 1000; in your app. On application on create check if SharedPreferences contains version ( even if SP is not present ) it will return saved or default method.

If value of SP version if less then the current version in your code. Use the updated function which you intent to use.

And if user uninstalls and reinstalled the app then too you might want to register your calls again.



Related Topics



Leave a reply



Submit