Android environment variables settings

Setup Android Environment Variables

This article will provide you with a detailed guide to setup Android Environment variables. This article is a continuation of our previous articles on Android, where you learned how to download and install Android Studio bundle and then how to install additional Android SDK tools.

The main Android environment variables that you would have to set are ANDROID_HOME and Path variables. If you have followed our Appium Tutorial series from the beginning, then you would remember that this article is similar to our previous article where we setup Java environment variables. Let’s now start with the setup process.

Find the folder location where you installed Android SDK

In the first step we will try to find the folder path where we have installed Android SDK –

1. The default folder location where Android SDK is installed is – C:\Users\Anish\AppData\Local\Android\sdk. Please open this folder path and see if you have Android SDK folder in there with contents as shown below

Please note that if you try to open this folder location by going to each folder one by one (i.e. C > Users > YourUserName and so on… ), then you might not see the AppData folder as its a hidden folder. So, you will have to make hidden folders visible first

2. Copy the SDK folder location once you find it. For us, this folder location is – C:\Users\Anish\AppData\Local\Android\sdk

Setup Android Environment Variables – Setup ANDROID_HOME

Follow the steps given below to setup ANDROID_HOME environment variable –

1. Click on Start menu. Then right click on Computer and select Properties option

2. This would open the System Properties window as shown below. Now from the Advanced Tab, click on Environment Variables button

3. From the Environment Variables window, click on New button from System variables section

4. Enter ANDROID_HOME in Variable Name field and SDK folder location (C:\Users\Anish\AppData\Local\Android\sdk) in Variable value field as shown in below image (Please enter the correct folder location that you have in your machine)

5. Click on OK button. ANDROID_HOME variable will now be added to System variables

With this, we have successfully added ANDROID_HOME variable. Let us now see how to add the Path variable.

Folder locations to be added to Path variable

In Android SDK folder, there are three specific folders that you need to add to the Path variable. These folders are –

  • platforms-tools folder which has path – C:\Users\Anish\AppData\Local\Android\sdk\platform-tools
  • tools folder which has path – C:\Users\Anish\AppData\Local\Android\sdk\tools
  • bin folder inside tools folder with path – C:\Users\Anish\AppData\Local\Android\sdk\tools\bin

Since we have already added ANDROID_HOME in System variables and its represented by – C:\Users\Anish\AppData\Local\Android\sdk, hence all these above three folder locations can be written as –

  • %ANDROID_HOME%\platform-tools
  • %ANDROID_HOME%\tools
  • %ANDROID_HOME%\tools\bin

Let us now add all these three folder locations in Path variable.

Setup Path Variable

Follow the steps given below to setup Path variable –

1. In the Environment variables window, check that there is a variable called Path under System variables

2. Select the Path variable and click on Edit button. Path variable window would be opened

3. Move over to the end in the Variable value text field. Put a semicolon (;) at the end and start adding all the 3 folder paths separated by semicolon (Semicolon acts as a delimiter between different folder locations added in the Path variable). You should have added all the 3 folder locations as this – ;%ANDROID_HOME%\platform-tools;%ANDROID_HOME%\tools;%ANDROID_HOME%\tools\bin

4. Click on OK button. All the three variables would now be added to the Path variables.

5. Close the Environment variable window by clicking on Ok button. With this, we have now successfully setup Path variable as well

Читайте также:  About android new versions

Verify that Android Environment Variables have been set correctly

To verify that all the Android Environment Variables are correctly setup, open command prompt and run this command: sdkmanager – -list (please note that there should be no space between the 2 hyphens, as shown in the below image). This would list down all the installed and available packages which would look a bit like something as shown below (please wait for 3-5 seconds for the list to be displayed)

You can also run this command: uiautomatorviewer in command prompt. This will open UI Automator Viewer window as displayed below.

You can now close UI Automator Window and the command prompt. Both the above commands verify that the Android Environment Variables have been setup correctly. If you face any issues with any of the steps, or if you get any different output using these commands, then please let us know using the comments section. With this we complete our article series on installing Android and setting up Android environment variables. We will now move over to our next article, which is downloading and installing Appium Desktop client.

Источник

Android Environments

Предисловие

Из далекого 2012, на просторах Хабра мне запомнился коммент:

Топик далеко не про хардварную составляющую. Разбирая свою проблему, я убедился в верности сия суждения и постарался навести порядок на своей пыльной полке.

Недавно ко мне обратился заказчик, который попросил добавить в его проект поддержку нескольких сервисов. Задача заключалась в том, что мне нужно было подключить сервис «А» и перед выкладкой приложения в продакшн, обкатать этот сервис на тестовом окружении. Я решил проанализировать свои предыдущие решения и… ужаснулся.

Для различного типа сборок я использовал различные конфигурационные файлы с описанием переменных окружения. Но проблема заключалась в том, что только лишь для проброса значения в реальный код, на каждый тип приходилось писать один и тот же код.

Проблема

Google дает нам возможность пробрасывать кастомные значения для каждой
сборки.

После анализа build.gradle скрипта, android tools заберет все значения buildConfigFileds из buildTypes и productFlavors и сгенерирует BuildConfig файлы для каждого типа сборок:

Никакой проблемы, на первый взгляд. Особенно, когда в вашем приложении не столь много флейворов и кастомных значений. В моем проекте их было >20 и 3 окружения (internal/alpha/production). Очевидно, что проблема для меня была одна — избавиться от бойлерплейта.

Не менее важная проблема — значения перменных окружения не должны быть отражены в вашем проекте. Даже в конфигурационном файле. Вы обязаны затрекать через VCS ваш build.gradle конфиг. Но вы не должны прописывать ваши ключи напрямую, для этого, вам необходим сторонний механизм(например файл, сервисы вашего CI). В моей практике было несколько проектов, где для release production сборки у меня не было доступа к значениям некоторых библиотек. Это уже проблема бизнеса и в его интересах не делать лишних затрат. Вы не должны использовать ключи предназначенные для продакшена во время отладки или внутреннего тестирования.

Способ решения проблемы

В одном из старых проектов, для хранения значений переменных окружения, мы использовали простые .properties файлы, которые предоставляли доступ к полям через классический key:value map. Проблему биндинга данный подход не решает. Но он решает проблему поставки данных, который следует применить. Кроме того, мы можем взять за основу .properties файлы как определенного рода контракт предоставления данных.

Если вернуться чуть назад, у нас есть промежуточный этап: из buildConfigField в поле класса BuildConfig. Но кто же это делает? Все довольно банально, за это отвечает gradle plugin который вы подключаете абсолютно во всех проектах Android.

Именно он отвечает за то, что после анализа вашего build.gradle файла будет сгенерирован класс BuildConfig для каждого флейвора со своим набором полей. Таким образом, я могу написать свое лекраство, которое расширит возможности com.android.application и избавит
меня от этой головной боли.

Решение проблемы выглядит следующим образом: предоставить контракт,
в котором будут описаны все ключи и значения для всех сборок.
Разложить конфигурационные файлы на подтипы. Отдать все плагину.

Решение

Выше мы разобрались со структурой решения, осталось дело за малым — воплотить все это в жизнь. Казалось бы, тривиальное решение и проблему можно решить простым расширением билд файла. Изначально, я так и поступил.

Читайте также:  Obnovlenie android для samsung

А вот тут сразу же возникли те трудности, о которых я и не задумывался — пыльная полка.Я решил «продать» свое реше коллегам. Я подготовил доку, пнул дело на обсуждение и… Понял, что все мы люди, а программисты — это ленивые люди. Никому не хочется вставлять неизвестный ему участок кода в проект, его же по хорошему нужно изучить, прочитать? А вдруг он нерабочий? А вдруг он делает еще что-то не так? Это же груви, а я его не знаю и непонятно как с ним работать. А уже давно переехал на котлин скрипт, а портировать с груви я не умею и проч.

Самое интересное, что все эти суждения уже исходили от меня, т.к. я понял, что меня такая интеграция решения не устраивает. Плюс, я заметил несколько моментов, которые мне бы очень хотелось бы улучшить. Внедрив решение в проект А, мне бы хотелось бы его поддержать в проекте Б. Выход один — надо писать плагин.

А какие же проблемы решит плагин и его удаленная поставка пользователю?

  • проблему ленивого програмиста. Нам лень углубляться в корень проблемы и возможные способы его решения. Нам куда проще взять что-то, что былоуже сделано до тебя и использовать это.
  • поддержка. Она включает в себя поддержку кода, его развитие и расшириения возможностей. При решении своей проблемы, я решал только проброспеременных окружения только лишь в код, совсем позабыв о возможности проброса в ресурсы.
  • качество кода. Бытует такое мнение, что некоторые разработчики даже не смотрят на open source код, который не покрыт тестами. На дворе 2019 и мы с легкостью можем подключить себе сервисы для отслеживания качества кода https://sonarcloud.io либо https://codecov.io/
  • конфигурация. Расширение билд файла заставляет меня изучить этот код и внести изменения вручную. В моем случае — мне не всегда нужно использовать конфигурацию для buildTypes либо productFlavors, хочу что-то одно или все сразу.
  • уборка пыльной полки. Я наконец-то навел порядок на одной из них и смог это решение по-дальше своей комнатушки.

В подробности и проблемы при написании плагина я вдаваться не буду, тянет на новый топик. Взять решение с его интеграцией, предложить свою идею либо внести свой вклад можно
здесь.

Источник

Configure Environment Variables with React Native Config for iOS and Android

While working on the Tempo Money Transfer Wallet mobile application for iOS and Android, which runs on the Stellar Blockchain, I had a need to use different variables for different environments. Out of habit, I tried to use the analog of the dotenv module for react native is react-native-dotenv and when configuring it, it did not work properly. Then I tried an alternative option with babel-plugin-transform-inline-environment-variables but even then a failure awaited me again with the correct configured module, the environment variables from the .env.development file were not captured.

For some reason, the combined use of the react-native-dotenv module and babel-plugin-transform-inline-environment-variables gave a result, but it turned out to be unstable, for some reason, the environment variables stopped capturing and I did not begin to figure it out (I didn’t have more time for this).

Benefits

I discovered for myself the react-native-config module and it seemed to be suitable for use for several reasons:

  • You can use environment variables not only in react native code, but also in native iOS and Android code (see an example of use below)
  • You can store variables in different files related to various development environments
  • You can switch between environment variables without any additional logic
  • In my opinion, more stable capture of environment variables by naive means of iOS and Android platforms without using the babel transcompiler

I wrote this article to share the experience of connecting this module to iOS. I will also add along the way a manual on how to add this module for Android and how to use environment variables in the native code of this platform.

So let’s move on to the practice 🙂

General setup

At first, we need to install react-native-config module to the project:

For React Native 0.60 or greater, for Android auto-linking is available, so you just need to install pods for iOS:

Second, we should make files, at the root of the project, where we will be storing our environment variables: .env.development and .env.production . So as you know we will have one file for development environment variables, the other for production.

Читайте также:  Детройт стать человеком модели андроидов

iOS setup

The main idea for iOS setups of a multi-file system for different environment variables is setting new scheme or edit existing:

  • Open your project ( ios folder from your root of the project) in Xcode.
  • Open Edit scheme. (Product → Scheme → Edit scheme…).

  • Duplicate your main scheme to dev (for .env.development variables ). My main scheme has reactNativeMultiEnv name, so I’ll add reactNativeMultiEnvDev for dev. Please click Duplicate Scheme button at bottom of the window and then change the name of the scheme at the top of the window.

Also, you can change the name of the scheme in Manage scheme (Product → Scheme → Manage Schemes…). Find the scheme you need to change, the select row of the table, then click on the scheme name and change it.

  • Make sure that you selected your duplicated scheme in Edit scheme. window. For me it’s reactNativeMultiEnvDev .

  • Open Build accordion, then click on Pre-actions , then click on + at the bottom of the window and then select New Run Script Action

And add two action scripts:

ensure that you select Provide build settings from as your project dir name, for me it is reactNativeMultiEnv .

Then make the same for your main scheme name, for me it is reactNativeMultiEnv , but make a change in the first action script file name from .env.development to .env.production .

Also, you can add, for example, stage environment variables by the same story: you should duplicate from the main scheme your scheme for your stage and add actions scripts in Pre-build with the correct file name.

  • Don’t forget to add the dependency to react-native-configin Podfile (the root of your project → ios folder → Podfile) :

Your code should be similar to my:

  • To read your config with environment variables in React Native code you should run the next code:
  • The final touch is needed to run your application with the dev scheme, you need to add to ‘scripts’ new command in the package.json file:

Your code should be similar to my:

Also, you can run other schemes, you just should change reactNativeMultiEnvDev scheme name from the previous command to yours.

iOS native usage

Read variables declared in .env files from your Obj-C classes like:

Android setup

Setup build types for environment variables is so much easier than for iOS. If you want to add different variables types you should go through the next steps:

  • Add to the top of android/app/build.gradle file next lines:

The naming of your build types is important! Make sure to use only lowercase letters with no special characters and append “release” at the end of the name of your custom build types, or they might not work.

In the file add next lines after apply plugin lines:

Also in the file find defaultConfig object and add the next line to it:

Replace com.myapp with the bundle identifier of your app.

That’s it! Now you can use your variables in native code or in React Native, but don’t forget to add the run script to package.json :

Also, you can run other schemes, you just should change dev scheme name from the previous command to yours.

Android native usage

Config variables set in .env are available to your Java classes via BuildConfig :

You can also read them from your Gradle configuration:

And use them to configure libraries in AndroidManifest.xml and others:

All variables are strings, so you may need to cast them. For instance, in Gradle:

Once again, remember variables stored in .env are published with your code, so DO NOT put anything sensitive there like your app signingConfigs .

Conclusion

So react-native-config is a simple way* to implement build types for environment variables and much more flexible if your React Native development doesn’t cover just JSX and you also working with platforms native code.

Источник

Оцените статью