Android apk studio


Build Multiple APKs | Android Studio

Although you should build a single APK to support all your target devices whenever possible, that might result in a very large APK due to files needed to support multiple screen densities or Application Binary Interfaces (ABIs). One way to reduce the size of your APK is to create multiple APKs that contain files for specific screen densities or ABIs.

Gradle can create separate APKs that contain only code and resources specific to each density or ABI. This page describes how to configure your build to generate multiple APKs. If you need to create different versions of your app that are not based on screen density or ABI, you can instead use build variants.

Configure your build for multiple APKs

To configure your build for multiple APKs, add a splits block to your module-level build.gradle file. Within the splits block, provide a density block that specifies how Gradle should generate per-density APKs, or an abi block that specifies how Gradle should generate per-ABI APKs. You can provide both density and ABI blocks, and the build system will create a an APK for each density and ABI combination.

Configure multiple APKs for screen densities

To create separate APKs for different screen densities, add a density block inside your splits block. In your density block, provide a list of desired screen densities and compatible screen sizes. The list of compatible screen sizes should only be used if you need specific <compatible-screens> elements in each APK's manifest.

The following Gradle DSL options are used to configure multiple APKs for screen densities:

enable If you set this element to true, Gradle generates multiple APKs based on the screen densities you define. The default value is false. exclude Specifies a comma-separated list of densities that Gradle should not generate separate APKs for. Use exclude if you want to generate APKs for most densities, but need to exclude a few densities that your app doesn't support. reset() Clears the default list of screen densities. Only use when combined with the include element to specify the densities you would like to add. The following snippet sets the list of densities to just ldpi and xxhdpi by calling reset() to clear the list, and then using include. reset() // Clears the default list from all densities to no densities. include "ldpi", "xxhdpi" // Specifies the two densities we want to generate APKs for. include Specifies a comma-separated list of densities that Gradle should generate APKs for. Only use in combination with reset() to specify an exact list of densities. compatibleScreens Specifies a comma-separated list of compatible screen sizes. This will inject a matching <compatible-screens> node in the manifest for each APK. This setting provides a convenient way to manage both screen densities and screen sizes in the same build.gradle section. However, using <compatible-screens> can limit the types of devices your app will work with. For alternative ways to support different screen sizes, see Support Multiple Screens.

Because each APK that's based on screen density includes a <compatible-screens> tag with specific restrictions about which screen types the APK supports, even if you publish several APKs, some new devices will not match your multiple APK filters. As such, Gradle always generates an additional universal APK that contains assets for all screen densities and does not include a <compatible-screens> tag. You should publish this universal APK along with your per-density APKs to provide a fallback for devices that do not match the APKs with a <compatible-screens> tag.

The following example generates a separate APK for each screen density listed in Range of screens supported, except ldpi, xxhdpi, and xxxhdpi. This is done by using exclude to remove three densities from the default list of all densities.

android { ... splits { // Configures multiple APKs based on screen density. density { // Configures multiple APKs based on screen density. enable true // Specifies a list of screen densities Gradle should not create multiple APKs for. exclude "ldpi", "xxhdpi", "xxxhdpi" // Specifies a list of compatible screen size settings for the manifest. compatibleScreens 'small', 'normal', 'large', 'xlarge' } } }

For a list of density names and screen size names, see How to Support Multiple Screens. For more details on distributing your app to specific screen types and devices, see Distributing to Specific Screens.

Configure multiple APKs for ABIs

To create separate APKs for different ABIs, add an abi block inside your splits block. In your abi block, provide a list of desired ABIs.

The following Gradle DSL options are used to configure multiple APKs per ABI:

enable If you set this element to true, Gradle generates multiple APKs based on the ABIs you define. The default value is false exclude Specifies a comma-separated list of ABIs that Gradle should not generate separate APKs for. Use exclude if you want to generate APKs for most ABIs, but need to exclude a few ABIs that your app doesn't support. reset() Clears the default list of ABIs. Only use when combined with the include element to specify the ABIs you would like to add. The following snippet sets the list of ABIs to just x86 and mips by calling reset() to clear the list, and then using include: reset() // Clears the default list from all ABIs to no ABIs. include "x86", "mips" // Specifies the two ABIs we want to generate APKs for. include Specifies a comma-separated list of ABIs that Gradle should generate APKs for. Only use in combination with reset() to specify an exact list of ABIs. universalApk If true, Gradle generates a universal APK in addition to per-ABI APKs. A universal APK contains code and resources for all ABIs in a single APK. The default value is false. Note that this option is only available in the splits.abi block. When building multiple APKs based on screen density, Gradle always generates a universal APK that contains code and resources for all screen densities.

The following example generates a separate APK for each ABI: x86, armeabi-v7a, and mips. This is done by using reset() to start with an empty list of ABIs, followed by include with a list of three ABIs that will each get an APK.

android { ... splits { // Configures multiple APKs based on ABI. abi { // Enables building multiple APKs per ABI. enable true // By default all ABIs are included, so use reset() and include to specify that we only // want APKs for x86, armeabi-v7a, and mips. // Resets the list of ABIs that Gradle should create APKs for to none. reset() // Specifies a list of ABIs that Gradle should create APKs for. include "x86", "armeabi-v7a", "mips" // Specifies that we do not want to also generate a universal APK that includes all ABIs. universalApk false } } }

For a list of supported ABIs, see Supported ABIs.

Configure versioning

By default, when Gradle generates multiple APKs, each APK will have the same version information, as specified in the module-level build.gradle file. Because the Google Play Store does not allow multiple APKs for the same app that all have the same version information, you need to ensure each APK has its own unique versionCode before you upload to the Play Store.

You can configure your module-level build.gradle file to override the versionCode for each APK. By creating a mapping that assigns a unique numeric value for each ABI and density you configure multiple APKs for, you can override the output version code with a value that combines the version code defined within the defaultConfig or productFlavors block with the numeric value assigned to the density or ABI.

In the following example, the APK for the mips ABI would get a versionCode of 2004 and the x86 ABI would get 3004. Assigning version codes in large increments, such as 1000, allows you to later assign unique version codes if you need to update your app. For example, if defaultConfig.versionCode iterates to 5 in a subsequent update, Gradle would assign a versionCode of 2005 to the mips APK and 3005 to the x86 APK.

Tip: If your build includes a universal APK, you should assign it a versionCode that's lower than that of any of your other APKs. Because Google Play Store installs the version of your app that is both compatible with the target device and has the highest versionCode, assigning a lower versionCode to the universal APK ensures that Google Play Store tries to install one of your APKs before falling back to the universal APK. The sample code below handles this by not overriding a universal APK's default versionCode.

android { ... defaultConfig { ... versionCode 4 } splits { ... } } // Map for the version code that gives each ABI a value. ext.abiCodes = ['armeabi-v7a':1, mips:2, x86:3] // For per-density APKs, create a similar map like this: // ext.densityCodes = ['mdpi': 1, 'hdpi': 2, 'xhdpi': 3] import com.android.build.OutputFile // For each APK output variant, override versionCode with a combination of // ext.abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode // is equal to defaultConfig.versionCode. If you configure product flavors that // define their own versionCode, variant.versionCode uses that value instead. android.applicationVariants.all { variant -> // Assigns a different version code for each output APK // other than the universal APK. variant.outputs.each { output -> // Stores the value of ext.abiCodes that is associated with the ABI for this variant. def baseAbiVersionCode = // Determines the ABI for this variant and returns the mapped value. project.ext.abiCodes.get(output.getFilter(OutputFile.ABI)) // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes, // the following code does not override the version code for universal APKs. // However, because we want universal APKs to have the lowest version code, // this outcome is desirable. if (baseAbiVersionCode != null) { // Assigns the new version code to versionCodeOverride, which changes the version code // for only the output APK, not for the variant itself. Skipping this step simply // causes Gradle to use the value of variant.versionCode for the APK. output.versionCodeOverride = baseAbiVersionCode * 1000 + variant.versionCode } } }

For more examples of alternate version code schemes, see Assigning version codes.

Build multiple APKs

Once you configure your module-level build.gradle file to build multiple APKs, click Build > Build APK to build all APKs for the currently selected module in the Project pane. Gradle creates the APKs for each density or ABI into the project's build/outputs/apk/ directory.

Gradle builds an APK for each density or ABI you configure multiple APKs for. If you enable multiple APKs for both densities and ABIs, Gradle creates an APK for each density and ABI combination. For example, the following build.gradle snippet enables building multiple APKs for mdpi and hdpi densities, and also x86 and mips ABIs.

... splits { density { enable true reset() include "mdpi", "hdpi" } abi { enable true reset() include "x86", "mips" } }

The output from the example configuration includes the following 4 APKs:

  • app-hdpiX86-release.apk: Contains code and resources for hdpi density and x86 ABI only.
  • app-hdpiMips-release.apk: Contains code and resources for hdpi density and mips ABI only.
  • app-mdpiX86-release.apk: Contains code and resources for mdpi density and x86 ABI only.
  • app-mdpiMips-release.apk: Contains code and resources for mdpi density and mips ABI only.

When building multiple APKs based on screen density, Gradle always generates a universal APK that includes code and resources for all densities, in addition to the per-density APKs. When building multiple APKs based on ABI, Gradle only generates an APK that includes code and resources for all ABIs if you specify universalApk true in the splits.abi block in your build.gradle file.

APK file name format

When building multiple APKs, Gradle uses APK filenames using the following scheme:

modulename-screendensityABI-buildvariant.apk

The scheme components are:

modulename Specifies the module name being built. screendensity If multiple APKs for screen density are enabled, specifies the screen density for the APK, such as "mdpi". ABI If multiple APKs for ABI are enabled, specifies the ABI for the APK, such as "x86". If multiple APKs for both screen density and ABI are enabled, Gradle concatenates the density name with the ABI name, for example "mdpiX86". If universalApk is enabled for per-ABI APKs, Gradle uses "universal" as the ABI portion of the universal APK filename. buildvariant Specifies the build variant being built, such as "debug".

For example, when building mdpi screen density APK for the debug version of "myApp", the APK filename is myApp-mdpi-debug.apk. The release version of "myApp" that is configured to build multiple APKs for both the mdpi screen density and the x86 ABI has an APK filename of myApp-mdpiX86-release.apk.

developer.android.com

Profile and Debug Pre-built APKs

  1. Attach Java sources
  2. Attach native debug symbols

Android Studio 3.0 allows you to profile and debug APKs without having to build them from an Android Studio project. However, you need to make sure you’re using a debuggable version of the APK.

To start debugging an APK, click Profile or debug APK from the Android Studio Welcome screen. Or, if you already have a project open, click File > Profile or debug APK from the menu bar. In the next dialog window, select the APK you want to import into Android Studio and click OK. You should see something similar to figure 1.

Figure 1. Importing a pre-built APK into Android Studio.

Note: When you import an APK into Android Studio, the IDE creates a new project in your home directory and makes a local copy of the target APK. This means that if you rebuild or update the original APK, you need to manually import the updated version into Android Studio again.

The Android view in the Project pane allows you to inspect the following contents of your APK:

  • APK file: Double-clicking the APK opens the APK analyzer.
  • manifests: The application manifests, extracted from the APK.
  • java: Contains Java code that Android Studio disassembles (into .smali files) from your APK’s DEX files. Each .smali file in this directory corresponding to a Java class.
  • cpp: If your app includes native code, this directory contains your APK’s native libraries (.so files).
  • External Libraries: Contains the Android SDK.

You can immediately use the Android profiler to start testing your app’s performance—however, the profiler currently works only with your app’s Java processes. To debug your app’s Java and native code using breakpoints, you need to first attach the Java sources and attach native debug symbols.

Attach Java sources

By default, Android Studio extracts Java code from your APK and saves them as .smali files. To debug the Java code using breakpoints, you need to attach the Java sources to each .smali file you want to debug.

To attach Java sources, proceed as follows:

  1. Double click on a .smali file from the Project pane (use the Android view). After opening the file, the editor displays a yellow warning banner asking you to select the Java sources, as shown in figure 1.
  2. Click Attach Java Sources at the top of the editor window.
  3. Navigate to the directory with the app’s Java source files and click Open.

In the Project window, the IDE replaces .smali files with their corresponding .java files. You can now add breakpoints and debug your app as you normally would.

Attach native debug symbols

If your APK includes native libraries (.so files) that don’t include debug symbols, the IDE shows you a warning in the Messages window, similar to the one shown in figure X. You can not debug the APK’s native code or use breakpoints without attaching debuggable native libraries. If you haven’t already done so, make sure to download the NDK and tools.

To attach debuggable native libraries, proceed as follows:

  1. Under the cpp directory in the Project window, double click a native library file that doesn’t include debug symbols. The editor shows a table of all the ABIs your APK supports.
  2. Click Add at the top right corner of the editor window.
  3. Navigate to the directory that includes the debuggable native libraries you want to attach and click OK.
  4. If the APK and debuggable native libraries were built using a different workstation, you need to specify local paths to the debug symbols by following these steps:
  5. Add local paths to missing debug symbols by editing the field under the Local Paths column in the Path Mappings section of the editor window, as shown in figure 2. The IDE automatically maps paths to a remote NDK to paths in your local NDK download.
  6. Click Apply.

    Figure 2. Providing paths to local debug symbols.

You should now see the native source files in the Project window. Open those native files to add breakpoints and debug your app as you normally would.

Known issue: When attaching debug symbols to an APK, both the APK and debuggable .so files must be built using the same workstation or build server.

developer.android.com

Android | Публикация приложения

Создание подписанного apk

Последнее обновление: 30.10.2015

После создания приложения, его тестирования и отладки мы можем приступить к его публикации. Суть публикации заключается в создании файла с расширением .apk, которое будет представлять приложение, и его последующее размещение в Google Play Market или на других внешних сайтах. По умолчанию в процессе отладки и создания приложения файл apk уже создается, и мы можем его найти в папке проекта по пути Название_проекта\app\build\outputs\apk. По умолчанию файл называется app-debug.apk и представляет debug-версию.

Но для полноценно публикации данного файла может оказаться недостаточно. И нам еще дополнительно надо произвести некоторую подготовку проекта к релизу. Для это следует указать в файле манифеста у элемента <manifest> установлены атрибуты android:versionCode и android:versionName. Также в файле манифеста элемент <application> не должен содержать атрибута android:debuggable

Кроме того, на этом этапе можно установить иконку для приложения, которая будет отображаться на рабочем экране гаджета, название приложения (атрибут android:label у элемента), а также можно задать лицензионное соглашение.

В файле манифеста также следует определить название пакета (атрибут package элемента <manifest>), которое будет использоваться для приложения в дальнейшем. По умолчанию при разработке в Android Studio пакеты приложений начинаются с com.example. Не стоит оставлять данное название, так как название пакета будет служить уникальным идентификатором вашего приложения. Например, ниже в моем случае названием пакета служит "com.maverics.eugene.telephonelist":

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.maverics.eugene.telephonelist" android:versionName="1.0" android:versionCode="1" > //.............................

При этом если в файлах кода java название пакета в начале файла также должно соответствовать пакету приложения.

Установка требований

На этапе подготовки к релизу также можно установить требования к API. Например, наше приложение имеет определеную минимальную версию ОС Android, поэтому мы можем установить в файле манифеста соответствующие атрибуты у элемента <uses-sdk>

  • android:minSdkVersion — минимальная версия Android

  • android:targetSdkVersion — оптимальная версия API

  • android:maxSdkVersion — максимальная версия системы

Например, пусть минимальная версия Jelly Beans 4.1.2, а оптимальная KitKat 4.4.4:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.maverics.eugene.telephonelist" android:versionName="1.0" android:versionCode="1" > <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19" /> //.............................

Подпись приложения

Когда все уже готово, приложение для Android должно быть подписано сертификатом, благодаря которому можно идентифицировать автора приложения. Когда мы тестируем приложение, устанавливая его через Android Studio на устройство, то оно подписывается автоматически. Но для создания релиз-версии нам надо произвести дополнительно ряд действий.

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

Во-первых, в Android Studio выберем в меню пункт Build -> Generate Signed APK. После этого нам откроется окно мастера:

Нажмем на кнопку Create new.... После этого нам откроется окно создания ключа:

Введем в поле Key store path путь к файлу сетификата, который будет создан. Если указанной папки не существует, то ее надо создать или определить существующую папку.

В поле Password/Confirm указываем пароль.

В поле Alias указываем псевдоним. Можно поставить произвольное название.

В поле First and Last Name вписываем имя и фамилию. И далее пишим подразделение, организацию, город, страну и код страны.

В конце нажимаем OK.

После этого автоматически обновится первое окошко:

Далее нажмем на кнопку Next:

Финальное окно покажет нам путь к каталогу, где будет находиться подписанное приложение apk в release-версии. Нажмем на Finish.

Теперь по указанному пути можно будет найти подписанный apk, который будет иметь название app-release.apk:

Мы можем переименовать файл, сохранив его расширение и выложить в Play Market или на любой сайт или сразу загрузить на мобильное устройство. После загрузки на телефон/планшет достоточно нажать на него, и с помощью стандартного установщика пакетов приложение будет установлено. Правда, здесь также надо учитывать, что если мы устанавливаем приложение не из Play Market, то в настройках надо разрешить установку из других источниках - Безопасность->Неизвестные источники (Разрешить установку приложений из других источников)

metanit.com

Установка apk и установка apk из Android Studio

Описываю проблему. При установке приложения из Android Studio, приложение запускается и продолжает нормально работать. Но если взять приложение из app/build/outputs/apk/app_debug и установить его просто так, то оно отваливается при запуске с ошибками.

11634-11634/galaxysoftware.minecraftcraftingmaster E/AndroidRuntime: FATAL EXCEPTION: main Process: galaxysoftware.minecraftcraftingmaster, PID: 11634 java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/galaxysoftware.minecraftcraftingmaster-1/base.apk"],nativeLibraryDirectories=[/data/app/galaxysoftware.minecraftcraftingmaster-1/lib/arm64, /vendor/lib64, /system/lib64]] at android.app.ActivityThread.installProvider(ActivityThread.java:5318) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4910) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4850) at android.app.ActivityThread.access$1800(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1457) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5582) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/galaxysoftware.minecraftcraftingmaster-1/base.apk"],nativeLibraryDirectories=[/data/app/galaxysoftware.minecraftcraftingmaster-1/lib/arm64, /vendor/lib64, /system/lib64]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:511) at java.lang.ClassLoader.loadClass(ClassLoader.java:469) at android.app.ActivityThread.installProvider(ActivityThread.java:5303) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4910)  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4850)  at android.app.ActivityThread.access$1800(ActivityThread.java:154)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1457)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5582)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  Suppressed: java.lang.ClassNotFoundException: com.google.firebase.provider.FirebaseInitProvider at java.lang.Class.classForName(Native Method) at java.lang.BootClassLoader.findClass(ClassLoader.java:781) at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) at java.lang.ClassLoader.loadClass(ClassLoader.java:504) ... 12 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

Вот build.gradle (app)

apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion '25.0.1' defaultConfig { multiDexEnabled true applicationId "galaxysoftware.minecraftcraftingmaster" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "10.10 beta" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:multidex:1.0.1' compile files('libs/YouTubeAndroidPlayerApi.jar') compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:design:25.3.1' compile 'com.android.support:support-v4:25.3.1' compile 'com.google.android.gms:play-services-appindexing:9.8.0' compile 'com.android.support:support-vector-drawable:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' }

ru.stackoverflow.com

Sign Your App | Android Studio

Android requires that all APKs be digitally signed with a certificate before they can be installed. This document describes how to sign your APKs using Android Studio, including creating and storing your certificate, signing different build configurations using different certificates, and configuring the build process to sign your APKs automatically.

Certificates and keystores

A public-key certificate, also known as a digital certificate or an identity certificate, contains the public key of a public/private key pair, as well as some other metadata identifying the owner of the key (for example, name and location). The owner of the certificate holds the corresponding private key.

When you sign an APK, the signing tool attaches the public-key certificate to the APK. The public-key certificate serves as as a "fingerprint" that uniquely associates the APK to you and your corresponding private key. This helps Android ensure that any future updates to your APK are authentic and come from the original author. The key used to create this certificate is called the app signing key.

A keystore is a binary file that contains one or more private keys.

Every app must use the same certificate throughout its lifespan in order for users to be able to install new versions as updates to the app. For more about the benefits of using the same certificate for all your apps throughout their lifespans, see Signing Considerations below.

Sign your debug build

When running or debugging your project from the IDE, Android Studio automatically signs your APK with a debug certificate generated by the Android SDK tools. The first time you run or debug your project in Android Studio, the IDE automatically creates the debug keystore and certificate in $HOME/.android/debug.keystore, and sets the keystore and key passwords.

Because the debug certificate is created by the build tools and is insecure by design, most app stores (including the Google Play Store) will not accept an APK signed with a debug certificate for publishing.

Android Studio automatically stores your debug signing information in a signing configuration so you do not have to enter it every time you debug. A signing configuration is an object consisting of all of the necessary information to sign an APK, including the keystore location, keystore password, key name, and key password. You cannot directly edit the debug signing configuration, but you can configure how you sign your release build.

For more information about how to build and run apps for debugging, see Build and Run Your App.

Expiry of the debug certificate

The self-signed certificate used to sign your APK for debugging has an expiration date of 365 days from its creation date. When the certificate expires, you will get a build error.

To fix this problem, simply delete the debug.keystore file. The file is stored in the following locations:

  • ~/.android/ on OS X and Linux
  • C:\Documents and Settings\<user>\.android\ on Windows XP
  • C:\Users\<user>\.android\ on Windows Vista and Windows 7, 8, and 10

The next time you build and run the debug build type, the build tools will regenerate a new keystore and debug key. Note that you must run your app, building alone does not regenerate the keystore and debug key.

Manage your key

Because your app signing key is used to verify your identity as a developer and to ensure seamless and secure updates for your users, managing your key and keeping it secure are very important, both for you and for your users. You can choose either to opt in to use Google Play App Signing to securely manage and store your app signing key using Google's infrastructure or to manage and secure your own keystore and app signing key.

Use Google Play App Signing

When using Google Play App Signing, you will use two keys: the app signing key and the upload key. Google manages and protects the app signing key for you, and you keep the upload key and use it to sign your apps for upload to the Google Play Store.

When you opt in to use Google Play App Signing, you export and encrypt your app signing key using the Play Encrypt Private Key tool provided by Google Play, and then upload it to Google's infrastructure. Then you create a separate upload key and register it with Google. When you are ready to publish, you sign your app using the upload key and upload it to Google Play. Google then uses the upload certificate to verify your identity, and re-signs your APK with your app signing key for distribution as shown in figure 1. (If you do not already have an app signing key, you can generate one during the sign-up process.)

Figure 1. Signing an app with Google Play App Signing

When you use Google Play App Signing, if you lose your upload key, or if it is compromised, you can contact Google to revoke your old upload key and generate a new one. Because your app signing key is secured by Google, you can continue to upload new versions of your app as updates to the original app, even if you change upload keys.

For more information about how to opt in to use Google Play App Signing, see Manage your app signing keys.

Manage your own key and keystore

Instead of using Google Play App Signing, you can choose to manage your own app signing key and keystore. If you choose to manage your own app signing key and keystore, you are responsible for securing the key and the keystore. You should choose a strong password for your keystore, and a separate strong password for each private key stored in the keystore. You must keep your keystore in a safe and secure place. If you lose access to your app signing key or your key is compromised, Google cannot retrieve the app signing key for you, and you will not be able to release new versions of your app to users as updates to the original app. For more information, see Secure your key, below.

If you manage your own app signing key and keystore, when you sign your APK, you will sign it locally using your app signing key and upload the signed APK directly to the Google Play Store for distribution as shown in figure 2.

Figure 2. Signing an app when you manage your own app signing key

Sign an APK

Regardless of how you choose to manage your key and keystore, you can use Android Studio to sign your APKs (with either the upload key or the app signing key), either manually, or by configuring your build process to automatically sign APKs.

If you choose to manage and secure your own app signing key and keystore, you will sign your APKs with your app signing key. If you choose to use Google Play App Signing to manage and secure your app signing key and keystore, you will sign your APKs with your upload key.

Generate a key and keystore

You can generate an app signing or upload key using Android Studio, using the following steps:

  1. In the menu bar, click Build > Generate Signed APK.
  2. Select a module from the drop down, and click Next.
  3. Click Create new to create a new key and keystore.

  4. On the New Key Store window, provide the following information for your keystore and key, as shown in figure 3.

    Figure 3. Create a new keystore in Android Studio.

    Keystore

    • Key store path: Select the location where your keystore should be created.
    • Password: Create and confirm a secure password for your keystore.

    Key

    • Alias: Enter an identifying name for your key.
    • Password: Create and confirm a secure password for your key. This should be different from the password you chose for your keystore
    • Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
    • Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.

    Once you complete the form, click OK.

  5. Continue on to Manually sign an APK if you would like to generate an APK signed with your new key, or click Cancel if you only want to generate a key and keystore, not sign an APK.
  6. If you would like to opt in to use Google Play App Signing, proceed to Manage your app signing keys and follow the instructions to set up Google Play App Signing.

Manually sign an APK

You can use Android Studio to manually generate signed APKs, either one at a time, or for multiple build variants at once. Instead of manually signing APKs, you can also configure your Gradle build settings to handle signing automatically during the build process. This section describes the manual signing process. For more about signing apps as part of the build process, see Configure the build process to automatically sign your APK.

To manually sign your APK for release in Android Studio, follow these steps:

  1. Click Build > Generate Signed APK to open the Generate Signed APK window. (If you just generated a key and keystore as described above, this window will already be open.)
  2. On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. (If you just created your keystore in the previous section, these fields are already populated for you.) Then click Next.

    Note: If you are using Google Play App Signing, you should specify your upload key here. If you are managing your own app signing key and keystore instead, you should specify your app signing key. For more information, see Manage your key above.

    Figure 4. Select a private key in Android Studio.

  3. On the next window, select a destination for the signed APK(s), select the build type, (if applicable) choose the product flavor(s), and click Finish.

    Figure 5. Generate signed APKs for the selected product flavors.

    Note: If your project uses product flavors, you can select multiple product flavors while holding down the Control key on Windows/Linux, or the Command key on Mac OSX. Android Studio will generate a separate APK for each selected product flavor.

When the process completes, you will find your signed APK in the destination folder you selected above. You may now distribute your signed APK through an app marketplace like the Google Play Store, or using the mechanism of your choice. For more about how to publish your signed APK to the Google Play Store, see Get Started with Publishing. To learn more about other distribution options, read Alternative Distribution Options.

In order for users to succesfully install updates to your app, you will need to sign your APKs with the same certificate throughout the lifespan of your app. For more about this and other benefits of signing all your apps with the same key, see Signing Considerations below. For more information about securing your private key and keystore, see Secure your key, below.

Configure the build process to automatically sign your APK

In Android Studio, you can configure your project to sign your release APK automatically during the build process by creating a signing configuration and assigning it to your release build type. A signing configuration consists of a keystore location, keystore password, key alias, and key password. To create a signing configuration and assign it to your release build type using Android Studio, use the following steps:

  1. In the Project window, right click on your app and click Open Module Settings.
  2. On the Project Structure window, under Modules in the left panel, click the module you would like to sign.
  3. Click the Signing tab, then click Add .
  4. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information.

    Figure 6. The window for creating a new signing configuration.

  5. Click the Build Types tab.
  6. Click the release build.
  7. Under Signing Config, select the signing configuration you just created.

    Figure 7. Select a signing configuration in Android Studio.

  8. Click OK.

Now every time you build your release build type using Android Studio, the IDE will sign the APK automatically, using the signing configuration you specified. You can find your signed APKs in the build/outputs/apk/ folder inside the project directory for the module you are building.

When you create a signing configuration, your signing information is included in plain text in your Gradle build files. If you are working in a team or sharing your code publicly, you should keep your signing information secure by removing it from the build files and storing it separately. You can read more about how to remove your signing information from your build files in Remove Signing Information from Your Build Files. For more about keeping your signing information secure, read Secure your key.

Sign each product flavor differently

If your app uses product flavors and you would like to sign each flavor differently, you can create additional signing configurations and assign them by flavor:

  1. In the Project window, right click on your app and click Open Module Settings.
  2. On the Project Structure window, under Modules in the left panel, click the module you would like to sign.
  3. Click the Signing tab, then click Add .
  4. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information.

    Figure 8. The window for creating a new signing configuration.

  5. Repeat steps 3 and 4 as necessary until you have created all your signing configurations.
  6. Click the Flavors tab.
  7. Click the flavor you would like to configure, then select the appropriate signing configuration from the Signing Config dropdown menu.

    Figure 9. Configure signing settings by product flavor.

    Repeat to configure any additional product flavors.

  8. Click OK.

You can also specify your signing settings in Gradle configuration files. For more information, see Configuring Signing Settings.

Sign Android Wear apps

If you are building an Android Wear app, the process for signing the app can differ from the process described on this page. See the information about packaging and publishing Android Wear apps.

Signing considerations

You should sign all of your APKs with the same certificate throughout the expected lifespan of your apps. There are several reasons why you should do so:

  • App upgrade: When the system is installing an update to an app, it compares the certificate(s) in the new version with those in the existing version. The system allows the update if the certificates match. If you sign the new version with a different certificate, you must assign a different package name to the app—in this case, the user installs the new version as a completely new app.
  • App modularity: Android allows APKs signed by the same certificate to run in the same process, if the apps so request, so that the system treats them as a single app. In this way you can deploy your app in modules, and users can update each of the modules independently.
  • Code/data sharing through permissions: Android provides signature-based permissions enforcement, so that an app can expose functionality to another app that is signed with a specified certificate. By signing multiple APKs with the same certificate and using signature-based permissions checks, your apps can share code and data in a secure manner.

If you plan to support upgrades for an app, ensure that your app signing key has a validity period that exceeds the expected lifespan of that app. A validity period of 25 years or more is recommended. When your key's validity period expires, users will no longer be able to seamlessly upgrade to new versions of your app.

If you plan to publish your apps on Google Play, the key you use to sign those APKs must have a validity period ending after 22 October 2033. Google Play enforces this requirement to ensure that users can seamlessly upgrade apps when new versions are available. If you use Google Play App Signing, Google ensures your apps are correctly signed and able to receive updates throughout their lifespans.

Secure your key

If you choose to manage and secure your app signing key and keystore yourself (instead of opting in to use Google Play App Signing), securing your app signing key is of critical importance, both to you and to the user. If you allow someone to use your key, or if you leave your keystore and passwords in an unsecured location such that a third-party could find and use them, your authoring identity and the trust of the user are compromised.

Note: If you use Google Play App Signing, your app signing key is kept secure using Google's infrastructure. You should still keep your upload key secure as described below. If your upload key is compromised, you can contact Google to revoke it and receive a new upload key.

If a third party should manage to take your key without your knowledge or permission, that person could sign and distribute apps that maliciously replace your authentic apps or corrupt them. Such a person could also sign and distribute apps under your identity that attack other apps or the system itself, or corrupt or steal user data.

Your private key is required for signing all future versions of your app. If you lose or misplace your key, you will not be able to publish updates to your existing app. You cannot regenerate a previously generated key.

Your reputation as a developer entity depends on your securing your app signing key properly, at all times, until the key is expired. Here are some tips for keeping your key secure:

  • Select strong passwords for the keystore and key.
  • Do not give or lend anyone your private key, and do not let unauthorized persons know your keystore and key passwords.
  • Keep the keystore file containing your private key in a safe, secure place.

In general, if you follow common-sense precautions when generating, using, and storing your key, it will remain secure.

Remove signing information from your build files

When you create a signing configuration, Android Studio adds your signing information in plain text to the module's build.gradle files. If you are working with a team or open-sourcing your code, you should move this sensitive information out of the build files so it is not easily accessible to others. To do this, you should create a separate properties file to store secure information and refer to that file in your build files as follows:

  1. Create a signing configuration, and assign it to one or more build types. These instructions assume you have configured a single signing configuration for your release build type, as described in Configure the Build Process to Automatically Sign Your APK, above.
  2. Create a file named keystore.properties in the root directory of your project. This file should contain your signing information, as follows: storePassword=myStorePassword keyPassword=mykeyPassword keyAlias=myKeyAlias storeFile=myStoreFileLocation
  3. In your module's build.gradle file, add code to load your keystore.properties file before the android {} block. ... // Create a variable called keystorePropertiesFile, and initialize it to your // keystore.properties file, in the rootProject folder. def keystorePropertiesFile = rootProject.file("keystore.properties") // Initialize a new Properties() object called keystoreProperties. def keystoreProperties = new Properties() // Load your keystore.properties file into the keystoreProperties object. keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) android { ... }

    Note: You could choose to store your keystore.properties file in another location (for example, in the module folder rather than the root folder for the project, or on your build server if you are using a continuous integration tool). In that case, you should modify the code above to correctly initialize keystorePropertiesFile using your actual keystore.properties file's location.

  4. You can refer to properties stored in keystoreProperties using the syntax keystoreProperties['propertyName']. Modify the signingConfigs block of your module's build.gradle file to reference the signing information stored in keystoreProperties using this syntax. android { signingConfigs { config { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile file(keystoreProperties['storeFile']) storePassword keystoreProperties['storePassword'] } } ... }
  5. Open the Build Variants tool window and ensure that the release build type is selected.
  6. Click Build > Build APK to build your release build, and confirm that Android Studio has created a signed APK in the build/outputs/apk/ directory for your module.

Because your build files no longer contain sensitive information, you can now include them in source control or upload them to a shared codebase. Be sure to keep the keystore.properties file secure. This may include removing it from your source control system.

Build and sign your app from command line

You do not need Android Studio to sign your app. You can sign your app from the command line using the apksigner tool or configure Gradle to sign it for you during the build. Either way, you need to first generate a private key using keytool. For example:

keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias

Note: keytool is located in the bin/ directory in your JDK. To locate your JDK from Android Studio, select File > Project Structure, and then click SDK Location and you will see the JDK location.

This example prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.jks, saving it in the current directory (you can move it wherever you'd like). The keystore contains a single key that is valid for 10,000 days.

Now you can build an unsigned APK and sign it manually or instead configure Gradle to sign your APK.

Build an unsigned APK and sign it manually

  1. Open a command line and navigate to the root of your project directory—from Android Studio, select View > Tool Windows > Terminal. Then invoke the assembleRelease task: gradlew assembleRelease

    This creates an APK named module_name-unsigned.apk in project_name/module_name/build/outputs/apk/. The APK is unsigned and unaligned at this point—it can't be installed until signed with your private key.

  2. Align the unsigned APK using zipalign:

    zipalign -v -p 4 my-app-unsigned.apk my-app-unsigned-aligned.apk

    zipalign ensures that all uncompressed data starts with a particular byte alignment relative to the start of the file, which may reduce the amount of RAM consumed by an app.

  3. Sign your APK with your private key using apksigner:

    apksigner sign --ks my-release-key.jks --out my-app-release.apk my-app-unsigned-aligned.apk

    This example outputs the signed APK at my-app-release.apk after signing it with a private key and certificate that are stored in a single KeyStore file: my-release-key.jks.

    The apksigner tool supports other signing options, including signing an APK file using separate private key and certificate files, and signing an APK using multiple signers. For more details, see the apksigner reference.

    Note: To use the apksigner tool, you must have revision 24.0.3 or higher of the Android SDK Build Tools installed. You can update this package using the SDK Manager.

  4. Verify that your APK is signed:

    apksigner verify my-app-release.apk

Configure Gradle to sign your APK

  1. Open the module-level build.gradle file and add the signingConfigs {} block with entries for storeFile, storePassword, keyAlias and keyPassword, and then pass that object to the signingConfig property in your build type. For example: android { ... defaultConfig { ... } signingConfigs { release { storeFile file("my-release-key.jks") storePassword "password" keyAlias "my-alias" keyPassword "password" } } buildTypes { release { signingConfig signingConfigs.release ... } } }

    Because Gradle reads paths relative to the build.gradle, the above example works only if my-release-key.jks is in the same directory as the build.gradle file.

    Note: In this case, the keystore and key password are visible directly in the build.gradle file. For improved security, you should remove the signing information from your build file.

  2. Open a command line in your project root directory and invoke the assembleRelease task: gradlew assembleRelease

This creates an APK named module_name-release.apk in project_name/module_name/build/outputs/apk/. This APK file is signed with the private key specified in your build.gradle file and aligned with zipalign.

And now that you've configured the release build with your signing key, the "install" task is available for that build type. So you can build, align, sign, and install the release APK on an emulator or device all with the installRelease task.

An APK signed with your private key is ready for distribution, but you should first read more about how to publish your app and review the Google Play launch checklist.

developer.android.com

Where do APK files get stored in Android Studio?

The are not stored but have to be generated . The procedure is =>

1 .) The first step in the process of generating a signed application APK file involves changing the build variant for the project from debug to release. This is achieved using the Build Variants tool window which can be accessed from the tool window quick access menu (located in the bottom left hand corner of the Android Studio main window.

2.) Once the Build Variants tool window is displayed, change the Build Variant settings for all the modules listed from debug to release.

3.) The project is now configured to build in release mode. The next step is to configure signing key information for use when generating the signed application package.

4.) To create a keystore file, select the Build -> Generate Signed APK… menu option to display the Generate Signed APK Wizard dialog.

5.) In the event that you have an existing release keystore file, click on the Choose existing… button and navigate to and select the file. In the event that you have yet to create a keystore file, click on the Create new… button to display the New Key Store dialog . Click on the button to the right of the Key store path field and navigate to a suitable location on your file system, enter a name for the keystore file (for example release.keystore.jks) and click on the OK button.

6.) The New Key Store dialog is now divided into two sections. The top section relates to the keystore file. In this section, enter a strong password with which to protect the keystore file into both the Password and Confirm fields. The lower section of the dialog relates to the release key that will be stored in the key store file.

7.) The next step is to generate a new private key which will be used to sign the application package. Within the Key section of the New Key Store dialog, enter the following details:

  • An alias by which the key will be referenced. This can be any sequence of characters, though only the first 8 are used by the system.
  • A suitably strong password to protect the key.
  • The number of years for which the key is to be valid (Google recommends a duration in excess of 27 years).

In addition, information must be provided for at least one of the remaining fields (for example your first and last name or organization name).

8.) Once the information has been entered, click on the Next button to proceed with the package creation.

9.) The next task to be performed is to instruct Android Studio to build the application APK package file in release mode and then sign it with the newly created private key. At this point the Generate Signed APK Wizard dialog should still be displayed with the keystore path, passwords and key alias fields populated with information.

10.) Assuming that the settings are correct, click on the Next button to proceed to the APK generation screen. Within this screen, review the Destination APK path: setting to verify that the location into which the APK file will be generated is acceptable. In the event that another location is preferred, click on the button to the right of the text field and navigate to the desired file system location.

11.) Enable the Run ProGuard checkbox (ProGuard performs a series of optimization and verification tasks that result in smaller and more efficient byte code) before clicking on the Finish button. At this point the Gradle system will compile the application in release mode. Once the build is complete, a dialog will appear providing the option to open the folder containing the APK file in an explorer window.

12.) At this point the application is ready to be submitted to the Google Play store.

The private key generated as part of this process should be used when signing and releasing future applications and, as such, should be kept in a safe place and securely backed up.

The final step in the process of bringing an Android application to market involves submitting it to the Google Play Developer Console. Once submitted, the application will be available for download from the Google Play App Store.

www.quora.com

Build and Run Your App

Android Studio sets up new projects to deploy to the Android Emulator or a connected device with just a few clicks. Once your app is installed, Instant Run allows you to push code changes without building a new APK.

To build and run your app, select Run > Run in the menu bar (or click Run in the toolbar). If it's the first time running the app, Android Studio asks you to select a deployment target as shown in figure 1. Select a device to install and run your app.

Figure 1. The Select Deployment Target dialog shows available devices

If the dialog says, "No USB devices or running emulators detected," then you need to set up and connect your device or launch an emulator by clicking a device listed under Available Virtual Devices. If there are no virtual devices listed, click Create New Virtual Device and follow the Virtual Device Configuration wizard (see Create and Manage Virtual Devices).

To display the Select Deployment Target dialog, either deselect Use same device for future launches or stop the app with Run > Stop app or Stop , and then start it again.

Note: You can also deploy your app in debug mode by clicking Debug . Running your app in debug mode allows you to set breakpoints in your code, examine variables and evaluate expressions at run time, and run debugging tools. To learn more, see Debug Your App.

Change the run/debug configuration

When you run your app for the first time, Android Studio uses a default run configuration. The run configuration specifies the module to run, package to deploy, activity to start, target device, emulator settings, logcat options, and more.

The default run/debug configuration launches the default project activity and uses the Select Deployment Target dialog for target device selection. If the default settings don't suit your project or module, you can customize the run/debug configuration, or even create a new one, at the project, default, and module levels. To edit a run/debug configuration, select Run > Edit Configurations. For more information, see Create and Edit Run/Debug Configurations.

Change the build variant

By default, Android Studio builds the debug version of your app, which is intended only for use during development, when you click Run.

To change the build variant Android Studio uses, select Build > Select Build Variant in the menu bar (or click Build Variants in the tool windows bar), and then select a build variant from the drop-down menu. By default, new projects are set up with two build variants: a debug and release variant. You need to build the release variant to prepare your app for public release.

To build other variations of your app, each with different features or device requirements, you can define additional build variants.

Build your project

The Run button compiles and installs the APK, but there are other options in the Build menu that you might want to use to compile parts or all of your project. Before you select any of the build options listed in table 1, you need to select the buid variant you want to build.

Table 1. Build options in the Build menu.

Menu Item Description
Make Module Compiles all source files in the selected module that have been modified since the last build, and all modules the selected module depends on recursively. The compilation includes dependent source files and any associated build tasks. You can select the module to build by selecting either the module name or one of its files in the Project window. This command does not generate an APK.
Make Project Makes all modules.
Clean Project Deletes all intermediate/cached build files.
Rebuild Project Runs Clean Project for the selected build variant and produces an APK.
Build APK(s)

Builds an APK of all the application modules in the current project for their selected variant. When the build completes, a confirmation notification appears, providing a link to the APK file and a link to open it in APK Analyzer.

If the build variant you've selected is a debug build type, then the APK is signed with a debug key and it's ready to install. If you've selected a release variant, then, by default, the APK is unsigned and you must manually sign the APK. However, you can instead configure the build process to automatically sign your APK.

All built APKs are saved in project-name/module-name/build/outputs/apk/.

Generate Signed APK Brings up a dialog with a wizard to set up a new signing configuration. For more information, see Sign an APK.

Note: The Run button builds an APK with testOnly="true", which means the APK can only be installed via adb (which Android Studio uses). If you want a debuggable APK that people can install without adb, select your debug variant and click Build > Build APK(s).

For details about the gradel steps taken for each command, open the Gradle Console. For more information about gradle and the build process, see Configure Your Build.

Monitor the build process

You can view details about the build process by clicking View > Tool Windows > Gradle Console (or by clicking Gradle Console in the tool window bar). The console displays each task that Gradle executes in order to build your app, as shown in figure 2.

Figure 2. The Gradle Console in Android Studio

If your build variants use product flavors, Gradle also invokes tasks to build those product flavors. To view the list of all available build tasks, click View > Tool Windows > Gradle (or click Gradle in the tool window bar).

If an error occurs during the build process, the Messages window appears to describe the issue. Gradle may recommend some command-line options to help you resolve the issue, such as --stacktrace or --debug. To use command-line options with your build process:

  1. Open the Settings or Preferences dialog:
    • On Windows or Linux, select File > Settings from the menu bar.
    • On Mac OSX, select Android Studio > Preferences from the menu bar.
  2. Navigate to Build, Execution, Deployment > Compiler.
  3. In the text field next to Command-line Options, enter your command-line options.
  4. Click OK to save and exit.

Gradle will apply these command-line options the next time you try building your app.

About Instant Run

In Android Studio 2.3 and higher, Instant Run significantly reduces the time it takes to update your app with code and resource changes. After deploying your app to a target device running Android 5.0 (API level 21) or higher, you can click Apply Changes to push certain code and resource changes to your running app without building a new APK—and, in some cases, without even restarting the current activity. The Run and Debug buttons are always available to you when you want to push your changes and force an app restart. However, you may find that using the Apply Changes button provides a faster workflow for most incremental changes to your app.

Tip: You can also press Control + F10 (or Control + Command + R on Mac) to apply changes with Instant Run.

The Apply Changes action is available only when you meet the following conditions:

  • Build your app using a debug build variant.
  • Use Android plugin for Gradle version 2.3.0 or higher.
  • Set minSdkVersion to 15 or higher in your app's module-level build.gradle file.
  • Deploy your app to a target device running Android 5.0 (API level 21) and higher.

For more information about enabling Instant Run, go to the section about configuring your project.

Instant Run pushes your changes by performing a hot swap, warm swap, or cold swap—the type of swap it performs depends on the type of change you made. When you click Apply Changes after making a code or resource change to your running app, Instant Run automatically determines the best way to push your change to the target device, as described in the following table.

Clicking Run (or Debug ) forces a cold swap and an app restart. If you make a change to the app manifest or a resource referenced by the manifest, Android Studio always pushes your changes with a full APK reinstall.

Code Change Apply Changes Behavior
  • Change implementation code of an existing method

Performs a hot swap: This is the fastest type of swap and makes changes visible much more quickly. Your application keeps running and a stub method with the new implementation is used the next time the method is called.

Hot swaps do not re-initialize objects in your running app. Before you see certain updates, you may need to either restart the current activity, by selecting Run > Restart Activity, or restart your app, by clicking Run (or Debug ). By default, Android Studio automatically restarts the current activity after performing a hot swap. If you do not want this behavior, you can disable automatic activity restarts.

  • Change or remove an existing resource
Performs a warm swap: This swap is still very fast, but Instant Run must restart the current activity when it pushes the changed resources to your app. Your app keeps running, but a small flicker may appear on the screen as the activity restarts—this is normal.
Structural code changes, such as:
  • Add, remove, or change:
    • an annotation
    • an instance field
    • a static field
    • a static method signature
    • an instance method signature
  • Change which parent class the current class inherits from
  • Change the list of implemented interfaces
  • Change a class's static initializer
  • Reorder layout elements that use dynamic resource IDs

Performs a cold swap: This swap is a bit slower because, although a new APK is not required, Instant Run must restart the whole app when it pushes structural code changes.

  • Change the app manifest
  • Change resources referenced by the app manifest
  • Change an Android system UI element, such as a widget or notification

When making changes to the app's manifest or resources referenced by the manifest, clicking Apply Changes redeploys a full build of your app with those changes. This is because certain information about the app, such as its name, app icon resources, and intent filters, are determined from the manifest when the APK is installed on the device.

If your build process automatically updates any part of the app manifest, such as automatically iterating versionCode or versionName, you will not be able to benefit from the full performance of Instant Run. When using Instant Run, you should disable automatic updates to any part in the app manifest in your debug build variants.

When updating an Android system UI element, such as a widget or notification, you need to click Run (or Debug ).

Note: If you need to restart your app after a crash, do not launch it from your target device. Restarting your app from your target device does not apply any of your code changes since the last cold swap or incremental build. To launch your app with all your recent changes, click Run (or Debug ) from Android Studio.

Disable automatic activity restart

When performing a hot swap, your app keeps running but Android Studio automatically restarts the current activity. To disable this default setting:

  1. Open the Settings or Preferences dialog:
    • On Windows or Linux, select File > Settings from the menu bar.
    • On Mac OSX, select Android Studio > Preferences from the menu bar.
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Restart activity on code changes.

If automatic activity restart is disabled, you can manually restart the current activity from the menu bar by selecting Run > Restart Activity.

Configure your project for Instant Run

Android Studio enables Instant Run by default for projects built using Android plugin for Gradle 2.3.0 and higher.

To update an existing project with the latest version of the plugin:

  1. Open the Settings or Preferences dialog.
  2. Navigate to Build, Execution, Deployment > Instant Run and click Update Project, as shown in figure 3.

    If the option to update the project does not appear, it’s already up-to-date with the latest Android plugin for Gradle. But make sure the box next to Enable Instant Run is checked.

    Figure 3. Updating the Android plugin for Gradle for an existing project

To start using Instant Run, you also need to change the build variant to a debug version of your app and deploy it to a target device running Android 5.0 (API level 21) or higher. To learn about more techniques that speed up your build, read Optimize Your Build Speed

Exclude your project from Windows Defender

On Windows systems, Windows Defender may cause slowdowns while using Instant Run. If you are using Windows Defender, you should exclude your Android Studio project folder from Windows Defender malware scans.

Improve build times when using Crashlytics

If your version of the Fabric Gradle plugin is lower than 1.21.6, Crashlytics may cause slower build times. To improve build performance while developing your app, you can either update the plugin to the latest version or disable Crashlytics for your debug build variant.

Limitations of Instant Run

Instant Run is designed to speed up the build and deploy process in most situations. However, there are some aspects to using Instant Run that might affect its behavior and compatibility with your app. If you experience any other issues while using Instant Run, please enable extra logging and report a bug.

Apps don't launch on some physical devices

Some device manufacturers block apps from automatically launching after being installed on the device. When deploying your app to a physical device using Android Studio 2.3, this restriction breaks the intended behavior of Instant Run and causes the following error output: Error: Not found; no service started. To fix this issue, update Android Studio to 2.3.1 or higher.

Debug mode always uses cold swaps

On Android Studio 2.3, if you deploy your app by clicking Debug , pushing subsequent code changes by clicking Apply Changes always results in a cold swap. To learn more, go to issue #234401.

Deploying to multiple devices

Instant Run uses different techniques to perform hot, warm, and cold swaps that are specific to the API level of the target device. For this reason, while deploying an app to multiple devices at once, Android Studio temporarily turns off Instant Run.

Multidexing your app

If minSdkVersion is set to 21 or higher, Instant Run automatically configures your app for multidex. Because Instant Run only works with the debug version of your app, you may need to configure your app for multidex when deploying your release build variant.

Running instrumented tests and performance profilers

Instrumented tests load both the debug APK and a test APK into the same process on a test device, allowing control methods to override the normal lifecycle of the app and perform tests. While running or debugging instrumented tests, Android Studio does not inject the additional methods required for Instant Run and turns the feature off.

While profiling an app, you should disable Instant Run. There is a small performance impact when using Instant Run and a slightly larger impact when overriding methods with a hot swap. This performance impact could interfere with information provided by performance profiling tools. Additionally, the stub methods generated with each hot swap can complicate stack traces.

Using third-party plugins

Android Studio temporarily disables the Java Code Coverage Library (JaCoCo) and ProGuard while using Instant Run. Because Instant Run only works with debug builds, this does not affect your release build.

Certain third-party plugins that perform bytecode enhancement may cause issues with how Instant Run instruments your app. If you experience these issues, but want to continue using Instant Run, you should disable those plugins for your debug build variant. You can also help improve compatibility with third-party plugins by filing a bug.

Pushing changes to multi-process apps

Instant Run only instruments your app's main process in order to perform hot swaps and warm swaps. When pushing code changes to other app processes, such as changes to a method implementation or an existing resource, Instant Run performs a cold swap.

Launching your app in a Work profile

If you run your app with Instant Run and open your app using a Work profile (or other secondary profile), your app will crash because the instrumented DEX files used by Instant Run are accessible only from the primary profile's user space.

If you want to continue using Instant Run, just avoid opening your app with the Work profile and be sure your run configuration does not use the --user user_id flag.

If you need to use your app with the Work profile, we recommend you create a new run configuration that includes the --user user_id flag, specifying the Work profile user ID. You can find the user ID by executing adb shell pm list users from command line. When you use the --user flag, Android Studio disables Instant Run for only that deployment; Instant Run will work again when you switch to a configuration without the --user flag.

Disable Instant Run

To disable Instant Run:

  1. Open the Settings or Preferences dialog.
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Enable Instant Run.

developer.android.com


Смотрите также