Farrukh Najmi
Farrukh Najmi

Reputation: 5316

Specify system property on launch of application

I need to specify a System Property when launching my android application from Android Studio / gradle. I cant figure out ho to do that.

Background is that my app needs to know the URL of the server it talks to. The default needs to be overridden during testing and development. I have code in the app that merges system properties on top of application properties read from a property file under assets folder. Now all I need is the ability to launch the app specifying a system property somehow.

TIA for your help.

Upvotes: 1

Views: 256

Answers (2)

Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

You can accomplish this via build variants.

Add something like the following to your build.gradle:

android {
   //...

   productFlavors {
        local {
            applicationId "com.example.myapp.local"
            versionName "1.0-local"
        }
        staging {
            applicationId "com.example.myapp.staging"
            versionName "1.0-staging"
        }
        prod {
            applicationId "com.example.myapp.prod"
            versionName "1.0-prod"
        }
    }

and then create the following resource files

app/src
     |
     + local/res/values/strings.xml
     |
     + staging/res/values/strings.xml
     |
     + prod/res/values/strings.xml

Where each strings.xml has the appropriate endpoint:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="api_endpoint">http://10.0.2.2:3000</string>
</resources>

Then, before running the app, select the build variant you want to run from the build variants tool window (e.g. localDebug or stagingRelease), and it'll have the intended string value that you can access as a resource.

Upvotes: 1

CodeWarrior
CodeWarrior

Reputation: 5176

You can always keep the URL in your SharedPreference. Whenever you are using it in development/testing you can take input from user and change it accordingly and save it again in SharedPreference. So your app will always know which server it's communicating to. If the user doesn't give any input then it'll take your default from asset folder else from SharedPreference.

Upvotes: 1

Related Questions