Pascal Bergeron
Pascal Bergeron

Reputation: 893

How to set an environment variable in Android?

I'm working on a project where I'm using the Android OS to develop a kiosk application for retail stores. For my purpose, I need to be able to set an environment variable on the Android device that:

  1. Is independent of any application;
  2. Is persistent across application and system reboots.

Bonus: if I can set the variable from adb, this would be even better.

Surprisingly, this has proved to be more difficult than anticipated.

  1. SharedPreferences doesn't cut the bill as the variable is dependent on the application that created it.
  2. Os.setenv sets a variable that is erased as soon as the application is closed or restarted.
  3. adb shell export seems to have no effect at all.

Anyone has tackled this issue?

Upvotes: 2

Views: 6690

Answers (2)

PPartisan
PPartisan

Reputation: 8231

You could use a ContentProvider if you want to expose data to other Android applications using the Android framework/in an Android way. Alternatively, if you have root access and prefer adb, then you may be able to use setprop and getprop:

$ adb shell setprop my.random.prop ok
$ adb shell getprop my.random.prop //outputs "ok"

If you have access to Android source you could add a command to init.rc that runs this at boot. Or, you could create a file in a location like data/local?

Edit: Allain has pointed out in the comments that adding persist to the property (i.e. persist.device.id) allows it to survive reboots.

Upvotes: 3

Priyanka
Priyanka

Reputation: 3709

do this to set using android studio into an app level build.gradle

paste your value file in src/main/res/raw folder

task copySecretKey(type: Copy) {
    def File secretKey = file "$System.env.YOUR_VARIABLE"
    from secretKey.getParent()
    include secretKey.getName()
    into 'src/main/res/raw'
    rename secretKey.getName(), "VALUE_OF_VARIABLE_FROM_RAW_FILE" // in my case it is credential.json
}
preBuild.dependsOn(copySecretKey)

Upvotes: 0

Related Questions