Search code examples
javaandroidsecurityhardcoded

Avoiding hardcoded ip addresses in Android


I use the following approach to store the server ip address in my android project so that the server url can be accessed by other classes.

   interface GlobalConstants{
       String SERVER_URL = "192.168.xx.xx";
   }

However, this approach requires recompiling each time the IP address changes and decompiling will expose the server url. Is there a better approach to initialize SERVER_URL ?

I tried System.setProperty() and System.getProperty() but still it is done at runtime. Is there a way to use something like a configuration file to store IP address and make it configurable?

Thanks in advance. :)


Solution

  • You can do this in gradle.build

     buildTypes {
            debug {
                buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
            }
            release {
                buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    

    Then you can acess it using BuildConfig class that android studio will generate.

    For example

    String url = BuildConfig.SERVER_URL + "endpoint";
    

    I hope this will help you.