Android build app version

Как получить номер сборки/версии вашего приложения для Android?

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

Нужно ли что-то делать с AndroidManifest.xml ?

ОТВЕТЫ

Ответ 1

И вы можете получить код версии с помощью этого

Ответ 2

Если вы используете плагин Gradle/Android Studio, от версии 0.7.0, код версии и имя версии доступны статически в BuildConfig , Убедитесь, что вы импортируете пакет приложений, а не другой BuildConfig :

Не требуется контекстный объект!

Также не забудьте указать их в файле build.gradle вместо AndroidManifest.xml .

Ответ 3

Немного короче, если вам просто нужно имя версии.

Ответ 4

Есть две части, которые вам нужны: Android: версия Код Android: версия Имя

versionCode — это число, и каждая версия приложения, которую вы отправляете в Маркет, должна иметь больший номер, чем последняя.

VersionName — это строка, которая может быть любой, какой вы хотите. Здесь вы определяете свое приложение как «1.0», «2.5» или «2 Alpha EXTREME!» или что угодно.

Ответ 5

Использование Gradle и BuildConfig

Получение VERSION_NAME из BuildConfig

Да, теперь это легко.

Возвращает ли пустая строка для VERSION_NAME?

Если вы получаете пустую строку для BuildConfig.VERSION_NAME , то читайте дальше.

Я продолжал получать пустую строку для BuildConfig.VERSION_NAME , потому что я не устанавливал versionName в файле сборки Grade (я перенес из ANT в Gradle). Итак, вот инструкции по обеспечению установки VERSION_NAME с помощью Gradle.

build.gradle

Примечание: это от мастерски Jake Wharton.

Удаление versionName и versionCode из AndroidManifest.xml

И поскольку теперь вы установили versionName и versionCode в файл build.gradle , вы также можете удалить их из своего файла AndroidManifest.xml , если они есть.

Ответ 6

Я не вижу необходимости получать его от менеджера пакетов

Ответ 7

Вот чистое решение, основанное на решении scottyab (отредактированное Xavi). Он показывает, как сначала получить контекст, если он не предоставлен вашим методом. Кроме того, он использует несколько строк вместо вызова нескольких методов на строку. Это облегчает вам задачу отладки вашего приложения.

Теперь, когда вы получили имя версии в String myVersionName , вы можете установить его в TextView или все, что вам нравится.

Ответ 8

Используйте класс BuildConfig

Ответ 9

Если вы используете PhoneGap, создайте собственный плагин PhoneGap:

Создайте новый класс в своем приложении:

В plugins.xml добавьте следующую строку:

В deviceready event добавьте следующий код:

Затем вы можете получить атрибут versionName, выполнив:

Ответ 10

Очень простой способ:

Ответ 11

Вот простой способ получить название версии и код версии

Ответ 12

Для пользователей xamarin используйте этот код, чтобы получить имя и код версии

1) Название версии:

Ответ 13

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

int versionCode = BuildConfig.VERSION_CODE;

Имя версии используется для ознакомления пользователей с разработчиками последовательности Developmemt. Вы можете добавить любое название версии по своему желанию.

String versionName = BuildConfig.VERSION_NAME;

Ответ 14

Если вы хотите использовать его в xml, добавьте строку ниже в файл gradle:

И затем используйте его на вашем xml следующим образом:

Ответ 15

Всегда делайте это с блоком try catch :

Ответ 16

Вот способ получения кода версии:

Ответ 17

У меня есть SOLVE this, используя класс предпочтений.

Ответ 18

Есть несколько способов получить versionCode и versionName программно.

  1. Получить версию из PackageManager . Это лучший способ для большинства случаев.
  1. Получите его из сгенерированного BuildConfig.java . Но обратите внимание, что если вы получите доступ к этим значениям в библиотеке, она вернет версию библиотеки, а не приложения, использующие эту библиотеку. Так что используйте только в небиблиотечных проектах!

Есть некоторые детали, кроме использования второго способа в проекте библиотеки. В новом плагине Android Gradle (3.0. 0+) некоторые функциональные возможности удалены. Итак, на данный момент, т.е. установка разных версий для разных вкусов работает некорректно.

Читайте также:  Smart tv приставка android с пультом

Код выше будет правильно установить значение в BuildConfig , но от PackageManager вы получите 0 и null , если вы не установили версию в по default конфигурации. Таким образом, ваше приложение будет иметь код 0 версии на устройстве.

Существует обходной путь — установите версию для выходного файла apk вручную:

Ответ 19

Нет, вам не нужно ничего делать с AndroidManifest.xml

Как правило, название и код версии вашего приложения находятся в файле gradle уровня приложения под тегом defaultConfig:

Примечание. Если вы хотите загрузить приложение в PlayStore, можно указать любое имя в качестве имени версии, но код версии должен отличаться от кода текущей версии, если это приложение уже находится в Play Store.

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

Ответ 20

для Api 28 PackageInfo.versionCode устарел, поэтому используйте следующий код:

Ответ 21

Этот код упоминался выше, но здесь он снова включен. Вам нужен блок try/catch, потому что он может вызывать «NameNotFoundException».

Надеюсь, это упростит для кого-то дорогу.:)

Ответ 22

Кому-то, кому нужна информация о BuildConfig для пользовательского интерфейса приложения, однако, хочет использовать эту информацию для настройки конфигурации задания CI или других, таких как я.

В вашем каталоге проектов автоматически создается файл BuildConfig.java, пока вы успешно строите проект.

Разделите информацию, необходимую для python script или других инструментов. Вот пример:

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

Источник

Build and release an Android app

During a typical development cycle, you test an app using flutter run at the command line, or by using the Run and Debug options in your IDE. By default, Flutter builds a debug version of your app.

When you’re ready to prepare a release version of your app, for example to publish to the Google Play Store, this page can help. Before publishing, you might want to put some finishing touches on your app. This page covers the following topics:

Note: Throughout this page, [project] refers to the directory that your application is in. While following these instructions, substitute [project] with your app’s directory.

Adding a launcher icon

When a new Flutter app is created, it has a default launcher icon. To customize this icon, you might want to check out the flutter_launcher_icons package.

Alternatively, you can do it manually using the following steps:

Review the Material Design product icons guidelines for icon design.

In the [project]/android/app/src/main/res/ directory, place your icon files in folders named using configuration qualifiers. The default mipmap- folders demonstrate the correct naming convention.

In AndroidManifest.xml , update the application tag’s android:icon attribute to reference icons from the previous step (for example, ).

To verify that the icon has been replaced, run your app and inspect the app icon in the Launcher.

Enabling Material Components

If your app uses Platform Views, you may want to enable Material Components by following the steps described in the Getting Started guide for Android.

  1. Add the dependency on Android’s Material in /android/app/build.gradle :

To find out the latest version, visit Google Maven.

  1. Set the light theme in /android/app/src/main/res/values/styles.xml :
  1. Set the dark theme in /android/app/src/main/res/values-night/styles.xml

Signing the app

To publish on the Play Store, you need to give your app a digital signature. Use the following instructions to sign your app.

On Android, there are two signing keys: deployment and upload. The end-users download the .apk signed with the ‘deployment key’. An ‘upload key’ is used to authenticate the .aab / .apk uploaded by developers onto the Play Store and is re-signed with the deployment key once in the Play Store.

  • It’s highly recommended to use the automatic cloud managed signing for the deployment key. For more information, see the official Play Store documentation.

Create an upload keystore

If you have an existing keystore, skip to the next step. If not, create one by either:

Running the following at the command line:

On Mac/Linux, use the following command:

On Windows, use the following command:

This command stores the upload-keystore.jks file in your home directory. If you want to store it elsewhere, change the argument you pass to the -keystore parameter. However, keep the keystore file private; don’t check it into public source control!

Note:

The keytool command might not be in your path—it’s part of Java, which is installed as part of Android Studio. For the concrete path, run flutter doctor -v and locate the path printed after ‘Java binary at:’. Then use that fully qualified path replacing java (at the end) with keytool . If your path includes space-separated names, such as Program Files , use platform-appropriate notation for the names. For example, on Mac/Linux use Program\ Files , and on Windows use «Program Files» .

The -storetype JKS tag is only required for Java 9 or newer. As of the Java 9 release, the keystore type defaults to PKS12.

Читайте также:  Диск андроид зачем нужен

Reference the keystore from the app

Create a file named [project]/android/key.properties that contains a reference to your keystore:

Warning: Keep the key.properties file private; don’t check it into public source control.

Configure signing in gradle

Configure gradle to use your upload key when building your app in release mode by editing the [project]/android/app/build.gradle file.

Add the keystore information from your properties file before the android block:

Load the key.properties file into the keystoreProperties object.

Find the buildTypes block:

And replace it with the following signing configuration info:

Release builds of your app will now be signed automatically.

Note: You may need to run flutter clean after changing the gradle file. This prevents cached builds from affecting the signing process.

For more information on signing your app, see Sign your app on developer.android.com.

Shrinking your code with R8

R8 is the new code shrinker from Google, and it’s enabled by default when you build a release APK or AAB. To disable R8, pass the —no-shrink flag to flutter build apk or flutter build appbundle .

Note: Obfuscation and minification can considerably extend compile time of the Android application.

Enabling multidex support

When writing large apps or making use of large plugins, you may encounter Android’s dex limit of 64k methods when targeting a minimum API of 20 or below. This may also be encountered when running debug versions of your app via flutter run that does not have shrinking enabled.

Flutter tool supports easily enabling multidex. The simplest way is to opt into multidex support when prompted. The tool detects multidex build errors and will ask before making changes to your Android project. Opting in allows Flutter to automatically depend on androidx.multidex:multidex and use a generated FlutterMultiDexApplication as the project’s application.

Note: Multidex support is natively included when targeting min sdk 21+.

You might also choose to manually support multidex by following Android’s guides and modifying your project’s Android directory configuration. A multidex keep file must be specified to include:

Also, include any other classes used in app startup. See the official Android documentation for more detailed guidance on adding multidex support manually.

Reviewing the app manifest

Review the default App Manifest file, AndroidManifest.xml , located in [project]/android/app/src/main and verify that the values are correct, especially the following:

application Edit the android:label in the application tag to reflect the final name of the app. uses-permission Add the android.permission.INTERNET permission if your application code needs Internet access. The standard template does not include this tag but allows Internet access during development to enable communication between Flutter tools and a running app.

Reviewing the build configuration

Review the default Gradle build file, build.gradle , located in [project]/android/app and verify the values are correct, especially the following values in the defaultConfig block:

applicationId Specify the final, unique (Application Id)appid versionCode & versionName Specify the internal app version number, and the version number display string. You can do this by setting the version property in the pubspec.yaml file. Consult the version information guidance in the versions documentation. minSdkVersion , compilesdkVersion , & targetSdkVersion Specify the minimum API level, the API level on which the app was compiled, and the maximum API level on which the app is designed to run. Consult the API level section in the versions documentation for details. buildToolsVersion Specify the version of Android SDK Build Tools that your app uses. Alternatively, you can use the Android Gradle Plugin in Android Studio, which will automatically import the minimum required Build Tools for your app without the need for this property.

Building the app for release

You have two possible release formats when publishing to the Play Store.

Note: The Google Play Store prefers the app bundle format. For more information, see Android App Bundle and About Android App Bundles.

Warning: Recently, the Flutter team has received several reports from developers indicating they are experiencing app crashes on certain devices on Android 6.0. If you are targeting Android 6.0, use the following steps:

If you build an App Bundle Edit android/gradle.properties and add the flag: android.bundle.enableUncompressedNativeLibs=false .

If you build an APK Make sure android/app/src/AndroidManifest.xml doesn’t set android:extractNativeLibs=false in the tag.

For more information, see the public issue.

Build an app bundle

This section describes how to build a release app bundle. If you completed the signing steps, the app bundle will be signed. At this point, you might consider obfuscating your Dart code to make it more difficult to reverse engineer. Obfuscating your code involves adding a couple flags to your build command, and maintaining additional files to de-obfuscate stack traces.

From the command line:

  1. Enter cd [project]
  2. Run flutter build appbundle
    (Running flutter build defaults to a release build.)

The release bundle for your app is created at [project]/build/app/outputs/bundle/release/app.aab .

Читайте также:  Май плей сити для андроид

By default, the app bundle contains your Dart code and the Flutter runtime compiled for armeabi-v7a (ARM 32-bit), arm64-v8a (ARM 64-bit), and x86-64 (x86 64-bit).

Test the app bundle

An app bundle can be tested in multiple ways—this section describes two.

Offline using the bundle tool

  1. If you haven’t done so already, download bundletool from the GitHub repository.
  2. Generate a set of APKs from your app bundle.
  3. Deploy the APKs to connected devices.

Online using Google Play

  1. Upload your bundle to Google Play to test it. You can use the internal test track, or the alpha or beta channels to test the bundle before releasing it in production.
  2. Follow these steps to upload your bundle to the Play Store.

Build an APK

Although app bundles are preferred over APKs, there are stores that don’t yet support app bundles. In this case, build a release APK for each target ABI (Application Binary Interface).

If you completed the signing steps, the APK will be signed. At this point, you might consider obfuscating your Dart code to make it more difficult to reverse engineer. Obfuscating your code involves adding a couple flags to your build command.

From the command line:

  1. Enter cd [project]
  2. Run flutter build apk —split-per-abi
    (The flutter build command defaults to —release .)

This command results in three APK files:

  • [project]/build/app/outputs/apk/release/app-armeabi-v7a-release.apk
  • [project]/build/app/outputs/apk/release/app-arm64-v8a-release.apk
  • [project]/build/app/outputs/apk/release/app-x86_64-release.apk

Removing the —split-per-abi flag results in a fat APK that contains your code compiled for all the target ABIs. Such APKs are larger in size than their split counterparts, causing the user to download native binaries that are not applicable to their device’s architecture.

Install an APK on a device

Follow these steps to install the APK on a connected Android device.

From the command line:

  1. Connect your Android device to your computer with a USB cable.
  2. Enter cd [project] .
  3. Run flutter install .

Publishing to the Google Play Store

For detailed instructions on publishing your app to the Google Play Store, see the Google Play launch documentation.

Updating the app’s version number

The default version number of the app is 1.0.0 . To update it, navigate to the pubspec.yaml file and update the following line:

The version number is three numbers separated by dots, such as 1.0.0 in the example above, followed by an optional build number such as 1 in the example above, separated by a + .

Both the version and the build number may be overridden in Flutter’s build by specifying —build-name and —build-number , respectively.

In Android, build-name is used as versionName while build-number used as versionCode . For more information, see Version your app in the Android documentation.

After updating the version number in the pubspec file, run flutter pub get from the top of the project, or use the Pub get button in your IDE. This updates the versionName and versionCode in the local.properties file, which are later updated in the build.gradle file when you rebuild the Flutter app.

Android release FAQ

Here are some commonly asked questions about deployment for Android apps.

When should I build app bundles versus APKs?

The Google Play Store recommends that you deploy app bundles over APKs because they allow a more efficient delivery of the application to your users. However, if you’re distributing your application by means other than the Play Store, an APK may be your only option.

What is a fat APK?

A fat APK is a single APK that contains binaries for multiple ABIs embedded within it. This has the benefit that the single APK runs on multiple architectures and thus has wider compatibility, but it has the drawback that its file size is much larger, causing users to download and store more bytes when installing your application. When building APKs instead of app bundles, it is strongly recommended to build split APKs, as described in build an APK using the —split-per-abi flag.

What are the supported target architectures?

When building your application in release mode, Flutter apps can be compiled for armeabi-v7a (ARM 32-bit), arm64-v8a (ARM 64-bit), and x86-64 (x86 64-bit). Flutter does not currently support building for x86 Android (See Issue 9253).

How do I sign the app bundle created by flutter build appbundle ?

How do I build a release from within Android Studio?

In Android Studio, open the existing android/ folder under your app’s folder. Then, select build.gradle (Module: app) in the project panel:

Next, select the build variant. Click Build > Select Build Variant in the main menu. Select any of the variants in the Build Variants panel (debug is the default):

The resulting app bundle or APK files are located in build/app/outputs within your app’s folder.

Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.

Источник

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