React native android bundle

Publishing to Google Play Store

Android requires that all apps be digitally signed with a certificate before they can be installed. In order to distribute your Android application via Google Play store it needs to be signed with a release key that then needs to be used for all future updates. Since 2017 it is possible for Google Play to manage signing releases automatically thanks to App Signing by Google Play functionality. However, before your application binary is uploaded to Google Play it needs to be signed with an upload key. The Signing Your Applications page on Android Developers documentation describes the topic in detail. This guide covers the process in brief, as well as lists the steps required to package the JavaScript bundle.

Generating an upload key​

You can generate a private signing key using keytool . On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin .

This command prompts you for passwords for the keystore and key and for the Distinguished Name fields for your key. It then generates the keystore as a file called my-upload-key.keystore .

The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

On Mac, if you’re not sure where your JDK bin folder is, then perform the following command to find it:

It will output the directory of the JDK, which will look something like this:

Navigate to that directory by using the command cd /your/jdk/path and use the keytool command with sudo permission as shown below.

Note: Remember to keep the keystore file private. In case you’ve lost upload key or it’s been compromised you should follow these instructions.

Setting up Gradle variables​

  1. Place the my-upload-key.keystore file under the android/app directory in your project folder.
  2. Edit the file

/.gradle/gradle.properties or android/gradle.properties , and add the following (replace ***** with the correct keystore password, alias and key password),

These are going to be global Gradle variables, which we can later use in our Gradle config to sign our app.

Note about using git: Saving the above Gradle variables in

/.gradle/gradle.properties instead of android/gradle.properties prevents them from being checked in to git. You may have to create the

/.gradle/gradle.properties file in your user’s home directory before you can add the variables.

Note about security: If you are not keen on storing your passwords in plaintext, and you are running macOS, you can also store your credentials in the Keychain Access app. Then you can skip the two last rows in

Adding signing config to your app’s Gradle config​

The last configuration step that needs to be done is to setup release builds to be signed using upload key. Edit the file android/app/build.gradle in your project folder, and add the signing config,

Generating the release AAB​

Run the following in a terminal:

Gradle’s bundleRelease will bundle all the JavaScript needed to run your app into the AAB (Android App Bundle). If you need to change the way the JavaScript bundle and/or drawable resources are bundled (e.g. if you changed the default file/folder names or the general structure of the project), have a look at android/app/build.gradle to see how you can update it to reflect these changes.

Note: Make sure gradle.properties does not include org.gradle.configureondemand=true as that will make the release build skip bundling JS and assets into the app binary.

The generated AAB can be found under android/app/build/outputs/bundle/release/app.aab , and is ready to be uploaded to Google Play.

Читайте также:  Fragment in android example android java

In order for Google Play to accept AAB format the App Signing by Google Play needs to be configured for your application on the Google Play Console. If you are updating an existing app that doesn’t use App Signing by Google Play, please check our migration section to learn how to perform that configuration change.

Testing the release build of your app​

Before uploading the release build to the Play Store, make sure you test it thoroughly. First uninstall any previous version of the app you already have installed. Install it on the device using the following command in the project root:

Note that —variant release is only available if you’ve set up signing as described above.

You can terminate any running bundler instances, since all your framework and JavaScript code is bundled in the APK’s assets.

Publishing to other stores​

By default, the generated APK has the native code for both x86 and ARMv7a CPU architectures. This makes it easier to share APKs that run on almost all Android devices. However, this has the downside that there will be some unused native code on any device, leading to unnecessarily bigger APKs.

You can create an APK for each CPU by changing the following line in android/app/build.gradle:

Upload both these files to markets which support device targeting, such as Google Play and Amazon AppStore, and the users will automatically get the appropriate APK. If you want to upload to other markets, such as APKFiles, which do not support multiple APKs for a single app, change the following line as well to create the default universal APK with binaries for both CPUs.

Enabling Proguard to reduce the size of the APK (optional)​

Proguard is a tool that can slightly reduce the size of the APK. It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using.

IMPORTANT: Make sure to thoroughly test your app if you’ve enabled Proguard. Proguard often requires configuration specific to each native library you’re using. See app/proguard-rules.pro .

To enable Proguard, edit android/app/build.gradle :

Migrating old Android React Native apps to use App Signing by Google Play​

If you are migrating from previous version of React Native chances are your app does not use App Signing by Google Play feature. We recommend you enable that in order to take advantage from things like automatic app splitting. In order to migrate from the old way of signing you need to start by generating new upload key and then replacing release signing config in android/app/build.gradle to use the upload key instead of the release one (see section about adding signing config to gradle). Once that’s done you should follow the instructions from Google Play Help website in order to send your original release key to Google Play.

Default Permissions​

By default, INTERNET permission is added to your Android app as pretty much all apps use it. SYSTEM_ALERT_WINDOW permission is added to your Android APK in debug mode but it will be removed in production.

Источник

React Native Generate APK — Debug and Release APK

An Android Package Kit (APK) is the package file format used by the Android OS for distribution and installation of mobile apps. It is similar to the .exe file you have on Windows OS, a .apk file is for android.

Читайте также:  Как изменить атрибуты файлов android

Debug APK

What can I use it for?

A debug .apk file will allow you to install and test your app before publishing to app stores. Mind you, this is not yet ready for publishing, and there are quite a few things you’ll need to do to before you can publish. Nevertheless, it’ll be useful for initial distribution and testing.

You’ll need to enable debugging options on your phone to run this apk.

Prerequisite:

How to generate one in 3 steps?

Step 1: Go to the root of the project in the terminal and run the below command:

react-native bundle —platform android —dev false —entry-file index.js —bundle-output android/app/src/main/assets/index.android.bundle —assets-dest android/app/src/main/res

Step 2: Go to android directory:

Step 3: Now in this android folder, run this command

There! you’ll find the apk file in the following path:
yourProject/android/app/build/outputs/apk/debug/app-debug.apk

Release APK

You will need a Java generated signing key which is a keystore file used to generate a React Native executable binary for Android. You can create one using the keytool in the terminal with the following command

keytool -genkey -v -keystore your_key_name.keystore -alias your_key_alias -keyalg RSA -keysize 2048 -validity 10000

Once you run the keytool utility, you’ll be prompted to type in a password. * Make sure you remember the password

You can change your_key_name with any name you want, as well as your_key_alias. This key uses key-size 2048, instead of default 1024 for security reason.

Step 2. Adding Keystore to your project

Firstly, you need to copy the file your_key_name.keystore and paste it under the android/app directory in your React Native project folder.

mv my-release-key.keystore /android/app

You need to open your android\app\build.gradle file and add the keystore configuration. There are two ways of configuring the project with keystore. First, the common and unsecured way:

This is not a good security practice since you store the password in plain text. Instead of storing your keystore password in .gradle file, you can stipulate the build process to prompt you for these passwords if you are building from the command line.

To prompt for password with the Gradle build file, change the above config as:

Place your terminal directory to android using:
cd android

For Windows,
gradlew assembleRelease

For Linux and Mac OSX:
./gradlew assembleRelease

Источник

Подключение React Native компонентов в релизной сборке Android

Не так давно я подключал компоненты React Native к нашему существующему приложению и потратил на это изрядное количество времени.

Связано это было с дополнительными требованиями к сборкам релизов, требующих создания bundle файла.

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

В старых версиях документации React Native (0.19), в случаях, если перед сборкой приложения у вас нет react.gradle файла, рекомендуется запускать команду связывания (bundling) вручную.

Получается довольно утомительно, можно получить ошибку, и не совсем ясно где взять файл react.gradle (или то, что он должен содержать).

Как правильно запустить задачу связывания (bundling task) в обычном процессе сборки приложения?

К счастью, в новой версии React Native использован лучший подход.

Если посмотреть в react-native directory, то вы легко найдете файл Gradle, который определяет задачу связывания. Это как раз тот react.gradle файл из документации.

Нам просто нужно подключить этот Gradle файл к существующему процессу сборки.

Перейдя по ссылке, вы узнаете, как правильно создать подписанный apk:

И обратите внимание на это:

«Если вам нужно изменить способ связывания комплекта JavaScript и/или ресурсов для рисования (например, если вы изменили имена файлов/папок по умолчанию или общую структуру проекта), перейдите на android/app/build.gradle, и вы узнаете как обновить проект, чтобы отразить эти изменения ».

Не правда ли похоже на подсказку? Но, по факту, не говорит в деталях о том как на самом деле настроить проект.

Читайте также:  Wileyfox swift обновление андроид

Итак, посмотрите файл приложения build.gradle.

Обратите внимание на раздел конфигурации:

Эти значения позволяют настроить поведение bundle task , включая такие параметры, как:

  • связывать в отладочной ( debug ) или в release сборках
  • путь к директории вашего проекта React Native
  • путь к js bundle
  • и еще много полезного…

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

Вот каким у нас стал файл конфигурации:

Благодаря этому мы можем правильно построить наш подписанный релизный apk с неповрежденным комплектом React Native js.

Есть еще одно важное замечание, о котором следует знать (из документации React Native): Убедитесь, что gradle.properties не включает org.gradle.configureondemand = true, так как в этом случаев ходе сборке пропуститься объединение JS и ресурсов в APK

Если вас заинтересовал React Native и вы хотите с ним работать, ссылки ниже помогут вам начать его изучать:

Источник

Bundling React Native during Android release builds

I’ve spent some time recently incorporating React Native components into our existing app.

This comes with the extra requirement of release builds requiring the creation of the bundle file.

I would have expected this to be a straightforward, well documented workflow, but was unfortunately a bit disappointed. It took a bit of digging, along with some trial and error, to finally automate the bundling process within our release builds.

Older versions of React Native’s docs (0.19) recommended running the bundling command manually before building your app if you don’t have a react.gradle file.

react-native bundle —platform android —dev false —entry-file index.android.js —bundle-output android/app/src/main/assets/index.android.bundle —assets-dest android/app/src/main/res/

This is tedious and error prone, and where to get the react.gradle file (or what it should contain) is not mentioned.

How do we properly hook the bundling task into the normal build process?

Thankfully newer versions of React Native support a better approach.

Looking into the react-native directory reveals a Gradle file that defines a bundling task. This is the react.gradle file that is mentioned in the docs.

We just need to hook this Gradle file into our existing build process.

The linked page below describes how to properly build a signed apk:

Generating Signed APK — React Native

Android requires that all apps be digitally signed with a certificate before they can be installed, so to distribute…

And notice this:

“If you need to change the way the JavaScript bundle and/or drawable resources are bundled (e.g. if you changed the default file/folder names or the general structure of the project), have a look at android/app/build.gradle to see how you can update it to reflect these changes.”

It hints at where to look, but doesn’t do a great job of indicating how to actually configure the project.

Again, the sample project is the key, look at the sample app’s build.gradle file.

Notice the config section:

These values allow the customization of the bundle task behavior including:

  • whether to bundle in debug or release builds
  • the path to your React Native project directory
  • the js bundle directory path
  • and more…

By customizing these config values in our top level app/build.gradle file, we were able to hook into the bundling command on all our release builds.

With this, we can correctly build our signed, release apk with the required React Native js bundle intact.

There is one last important note to be aware of. From the React Native documentation:

Make sure gradle.properties does not include org.gradle.configureondemand=true as that will make release build skip bundling JS and assets into the APK

To get started with React Native check out the links below:

Источник

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