Android make sdk error

Содержание
  1. Методы лечения различных ошибок в Android Studio при разработке проекта
  2. Устранение неполадок пакет SDK для Android
  3. Какие разрешения Android требуются?
  4. Данные аналитики не отображаются на портале
  5. Сбои не отображаются на портале
  6. Распространение и обновление в приложении блокируют автоматические тесты пользовательского интерфейса
  7. Каково влияние пакета SDK центра приложений на размер приложения Android?
  8. Защита значения секрета центра приложений
  9. Миграция с Жцентер на Maven Central
  10. Android build fails with Android SDK Build-Tools 31.0.0 #1288
  11. Comments
  12. kputh commented Jul 21, 2021
  13. Bug Report
  14. Problem
  15. What is expected to happen?
  16. What does actually happen?
  17. Information
  18. Command or Code
  19. Environment, Platform, Device
  20. Version information
  21. Checklist
  22. kputh commented Jul 21, 2021 •
  23. Workaround
  24. breautek commented Jul 21, 2021 •
  25. miketimofeev commented Jul 23, 2021
  26. breautek commented Jul 23, 2021 •
  27. pawan-logiciel commented Jul 24, 2021
  28. kputh commented Jul 26, 2021
  29. kputh commented Jul 26, 2021
  30. breautek commented Jul 26, 2021
  31. breautek commented Jul 26, 2021
  32. LucasFebatis commented Jul 27, 2021
  33. breautek commented Jul 27, 2021
  34. boredom2 commented Jul 31, 2021 •
  35. dattakadiyala commented Aug 4, 2021 •
  36. breautek commented Aug 4, 2021
  37. jaydrogers commented Aug 5, 2021 •
  38. The error I was seeing
  39. First, I had a different ENV var
  40. So I changed the command to:
  41. I then installed version 30.0.3:
  42. pcwSlide commented Aug 7, 2021
  43. NitzDKoder commented Aug 19, 2021
  44. breautek commented Aug 19, 2021
  45. pcwSlide commented Aug 19, 2021
  46. breautek commented Aug 19, 2021
  47. webb24h commented Aug 25, 2021
  48. The error I was seeing
  49. First, I had a different ENV var
  50. So I changed the command to:
  51. I then installed version 30.0.3:

Методы лечения различных ошибок в Android Studio при разработке проекта

Сегодня хотел бы поделиться своим анализом и способами лечением разных ошибок при разработке своего продукта в Android Studio. Лично я, не раз сталкивался с различными проблемами и ошибками при компиляции и/или тестировании мобильного приложения. Данный процесс, всегда однообразный и в 99% случаев и всегда нужно тратить n-колличество времени на его устранение. Даже, когда ты уже сталкивался с данной проблемой, ты все равно идешь в поисковик и вспоминаешь, как же решить ту или иную ситуацию.

Я для себя завел файлик, в котором отметил самые частые ошибки — потратив на это несколько часов и перечислил самые популярные ошибки (в дальнейшем планирую просто их запомнить), чтоб сократить свое время в дальнейшем.

Итак, начну по порядку с самой распространенной проблемы и дальше буду перечислять их по мере появления:

1) Если подчеркивает красным код, где используются ресурсы: R. — попробовать (но вероятно не поможет): Build -> Clean Project.

В принципе на Build -> Clean Project можно не терять времени, а лучше всего — слева переключиться на Project, открыть каталог .idea, затем каталог libraries и из него удалить все содержимое. Затем нажать кнопку Sync Project. А затем (если все еще красное, но скорее всего уже будет все ок ) Build -> Clean Project.

2) После внезапного выключения компьютера, после перезапуска может быть во всех проектах весь код красным. Перед этим может быть ошибка: Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of ‘adb version’. Есть три решения — первое помогло, второе нет (но может быть для другого случая), а третье — не пробовал:

а) File — Invalidate Caches/Restart — Invalidate and Restart

б) Закрыть студию. В корне папки проекта удалить файл(ы) .iml и папку .idea. Вновь запустить студию и импортировать проект.

в) Нажать Ctrl-Alt-O и запустить оптимизацию импорта.

Кстати, adb сервер можно проверить на версию (и работоспособность) и затем перезапустить:

3) Если Android Studio выдает приблизительно такую ошибку: Error:Execution failed for task ‘:app:dexDebug’.

Надо слева переключиться на опцию Project, найти и удалить папку build которая лежит в папке app, т.е. по пути app/build. Затем перестроить весь проект заново: Build -> Rebuild Project.

Такое же решение если ошибка типа: «не могу удалить (создать) папку или файл» и указан путь, который в ведет в app/build. Тоже удаляем папку build и ребилдим проект.

4) В сообщении об ошибке упоминается heap — виртуальная память. А ошибка обычно вызвана ее нехваткой, т.е. невозможностью получить запрашиваемый объем. Поэтому этот запрашиваемый объем надо уменьшить, т.е. переписать дефолтное значение (обычно 2048 MB которое можно изменить в настройках), на меньшее 1024 MB.

В файле проекта gradle.properties пишем:

5) Android Studio пришет примерно такую ошибку: Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to «83648b99316049d63656d7276cb19cc7e95d70a5»

Возможные причины (кроме необходимости регулярного обновления SDK):

а) Загруженный проект был скомпилирован с помощью уже несовместимого старого gradle плагина. В этом случае надо найти и подключить в своем build.gradle проекта этот более старый плагин. т.е. попробовать более старые версии, например: 1.1.3 (часто именно 1.1.x и подходит).

Найти все версии можно здесь.

б) Если в build.gradle проекта используется beta-версия плагина — это означает, что срок ее истек. Посмотреть последние релизы (продакшн и бета) можно также здесь:

6) Иногда при подключении сторонних библиотек могут дублироваться некоторые файлы (обычно связанные с лицензированием). В сообщении будет что-то содержащее слова: duplicate files. Решение — надо посмотреть в сообщении об ошибке или в документации подключенной сторонней библиотеки — какие именно файлы стали избыточными, и перечислить их в build.gradle модуля для исключения (exclude) из билда.

Читайте также:  Android checking sdk version

Это делается в директиве packagingOptions (которая, в свою очередь, находится в директиве android).

Источник

Устранение неполадок пакет SDK для Android

Какие разрешения Android требуются?

В зависимости от используемых служб требуются следующие разрешения.

  • Все службы: INTERNET , ACCESS_NETWORK_STATE
  • Распространение: REQUEST_INSTALL_PACKAGES , DOWNLOAD_WITHOUT_NOTIFICATION

Необходимые разрешения автоматически объединяются в манифест приложения пакетом SDK.

Ни одно из этих разрешений не требует утверждения пользователем во время выполнения, но все время установки имеет разрешения.

Данные аналитики не отображаются на портале

Убедитесь, что модули SDK интегрированы правильно.

Убедитесь, что включен правильный секрет приложения вместе с start() вызовом метода. Вы можете скопировать точный start() код, открыв приложение на портале и перейдя на страницу Начало работы.

Если вы хотите просмотреть журналы, отправляемые на серверную часть, измените уровень ведения журнала на verbose в приложении, и пакет SDK выведет журналы в консоли. Перед запуском пакета SDK вызовите приведенный ниже API.

Проверьте журналы, например «успешно настроен пакет SDK центра приложений» (на уровне журнала сведений), а затем проверьте, отображаются ли журналы запросов HTTPS.

Убедитесь, что устройство подключено.

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

Чтобы проверить, получены ли данные серверной части центра приложений, перейдите к разделу поток журнала в службе аналитики. События должны появиться после отправки.

Сбои не отображаются на портале

Убедитесь, что модули SDK интегрированы правильно.

Убедитесь, что включен правильный секрет приложения вместе с start() вызовом метода. Вы можете скопировать точный start() код, открыв приложение на портале и перейдя на страницу Начало работы.

Перезапустите приложение после сбоя. Наш пакет SDK пересылает журнал аварийного восстановления только после его перезапуска.

Если вы хотите просмотреть журналы, отправляемые на серверную часть, измените уровень ведения журнала на verbose в приложении, и пакет SDK выведет журналы в консоли. Перед запуском пакета SDK вызовите приведенный ниже API.

Проверьте журналы, например «успешно настроен пакет SDK центра приложений» (на уровне журнала сведений), а затем проверьте, отображаются ли журналы запросов HTTPS.

Убедитесь, что устройство подключено.

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

Если вы хотите проверить, обнаружила ли пакет SDK аварийное завершение следующего приложения, можно вызвать API, чтобы проверить, не завершилось приложение в последнем сеансе и покажет предупреждение. Или можно расширить обратный вызов аварийного восстановления, чтобы проверить, успешно ли он был отправлен на сервер.

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

Распространение и обновление в приложении блокируют автоматические тесты пользовательского интерфейса

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

Каково влияние пакета SDK центра приложений на размер приложения Android?

Пакет SDK для App Center предназначен для минимального влияния на размер установки приложения.

Чтобы проиллюстрировать это, мы создали пустое приложение Java с помощью шаблона «Пустое приложение» Android Studio. Мы создаем приложение в конфигурации выпуска и установили приложение на устройстве под управлением Android 7,0.

Тесты выполнялись без защиты.

Приведенные ниже числа могут различаться и зависеть от параметров сборки, поэтому следует рассмотреть их в виде грубого указания. Влияние пакета SDK на приложение будет еще ниже, если вы используете защиту.

Используемые модули центра приложений Размер экспортируемого APK Размер установки (сообщается об устройстве)
Нет (пустое приложение) 1,3 МБ 3,43 МБ
Аналитика Центра приложений 1,4 МБ 3,63 МБ
Сбой в центре приложений 1,4 МБ 3,70 МБ
Распространение через Центр приложений 1,4 МБ 3,71 МБ
Все модули центра приложений 1,4 МБ 3,82 МБ

Защита значения секрета центра приложений

app_secret — Это идентификатор приложения, необходимо узнать, к какому приложению применяется трафик, а также не может использоваться для извлечения или изменения существующих данных. Если ваше app_secret приложение предоставлено, самый большой риск отправит неправильные данные приложению, но это не повлияет на безопасность данных.

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

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

Миграция с Жцентер на Maven Central

Из-за прекращения поддержки жцентер все наши сборки были перемещены в центральный репозиторий Maven. Чтобы использовать центр приложений, необходимо добавить в mavenCentral() репозиторий в файле Gradle, как показано ниже.

Источник

Android build fails with Android SDK Build-Tools 31.0.0 #1288

Comments

kputh commented Jul 21, 2021

Bug Report

Problem

I get the following error:

The build seems to ignore the pinned Android Build-Tools version.

This issue started appearing in our build pipeline between July 19., 13:20 UTC and July 20., 08:38 UTC. I can’t tell when the Android SDK Build-Tools 31.0.0 were release, but cordova-android 10.0.0 was release July 20., 04:17 (timezone?). That may be no coincidence.

What is expected to happen?

The build should succeed.

What does actually happen?

The build fails.

Information

Command or Code

Environment, Platform, Device

Azure Pipelines, vmImage ‘macOS-10.15’, and local development (see below)

Version information

Project Installed Platforms:

Project Installed Plugins:

  • OS: macOS 11.4 (20F71) (darwin 20.5.0) x64
  • Node: v12.16.3
  • npm: 6.14.4

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

The text was updated successfully, but these errors were encountered:

kputh commented Jul 21, 2021 •

Workaround

My first attempt to work around this issue was upgrading to cordova-android 10.0.0, and my second one was pinning the Android SDK Build-Tools version as seen above. When both failed, uninstalling the offending dependency did the trick. It can be done in Android Studio or on the command line:

breautek commented Jul 21, 2021 •

Migrated this to cordova-android for you since this is the package that is responsible for handling the android environment.

Our supported API level on cordova-android@10 is API 30, so build-tools version 30 should work. I’ve placed this issue in the 11.x milestone because generally we only officially support the next API level in a major releases. However, if it is possible to fix this without introducing breaking changes, then we may include it in a future minor release.

Currently cordova-android will look for the latest installed version of build tools, which is probably a bad idea for this very reason. Which is why the uninstalling build-tools 31 is the necessary workaround.

miketimofeev commented Jul 23, 2021

@breautek am I right that none of these options will work and there is no way to pin the build-tools version?

breautek commented Jul 23, 2021 •

@breautek am I right that none of these options will work and there is no way to pin the build-tools version?

Correct, and further investigation on the «why» identifies another bug.

The desired build tools get set here:

buildToolsVersion cordovaConfig . LATEST_INSTALLED_BUILD_TOOLS

LATEST_INSTALLED_BUILD_TOOLS gets set by:

Lines 175 to 177 in 0ce6624

cordovaConfig . LATEST_INSTALLED_BUILD_TOOLS = doFindLatestInstalledBuildTools(
cordovaConfig . BUILD_TOOLS_VERSION
)

Where BUILD_TOOLS_VERSION is comes from the config shown in your docs screenshot. As the doFindLatestInstalledBuildTools function name might suggest, it finds the latest build tools version, with the parameter being the «minimum» required version.

In fact, this behaviour did change as cordova-android 9.1 did:

Lines 164 to 167 in c9108d8

if (ext . cdvBuildToolsVersion == null ) <
ext . cdvBuildToolsVersion = privateHelpers . findLatestInstalledBuildTools()
// ext.cdvBuildToolsVersion = project.ext.defaultBuildToolsVersion
>

And only used findLatestInstalledBuildTools if the user parameter wasn’t specified. I do believe this wasn’t intentional and this issue probably should be reported as a separate issue, which I’ve already done here.

pawan-logiciel commented Jul 24, 2021

Hey @kputh
In order to fix the issue, firstly go to the following location:

Then find the file d8 (Windows batch file) and rename it to dx.

Then find the file d8 (Executable Jar File) and rename is to dx.

Your problem will be solved now.

I have also the same problem which gets resolved with above solution

kputh commented Jul 26, 2021

@pawan-logiciel, thank you for the workaround. Unfortunately, I can’t use it in out build pipeline

kputh commented Jul 26, 2021

Sorry, I hit the wrong button.

breautek commented Jul 26, 2021

The PR #1293 should provide a better workaround (by fixing the actual gradle arg parameter).

Hoping it will be reviewed and be included in our patch release.

breautek commented Jul 26, 2021

We also merged in #1294 which will fix cordova-android to not blindly take in any build tools version, but limit the scope to use the latest patch of a particular major version. We are planning on doing a patch release sometime soon (cannot give any more details then that) so this should address the issue without using any actual parameters, though using the gradle argument to pin to a specific version might be still ideal.

As for supporting build tools 31, it looks like cordova android needs to use AGP 7 which also requires Java 11. These are all breaking changes, so I’ll leave this issue open and inside our 11.x milestone.

LucasFebatis commented Jul 27, 2021

I’m working with Ionic and it’s forcing me to use cordova-android 9.1.0 and I’m getting the same error build tools 31.0.0

I found out that in the cordovaLib module that is generated, in build.gradle it generates with this snippet

Which makes any attempt to change buildtools by environment variable or arguments impossible, because it will always use the most current version installed on the machine.

What is simple to be solved in a local development, boring but simple.

But now to update on my CI/CDs that already come with all versions available to me, what do I do?

I only see two work around

Create a vm image with the version of BuildTools I need (Too much work)

Create a step to replace the generated build.gradle with a template (Which is really annoying, since one day Android or Cordova or Ionic will fix these problems, and then I’ll have to discard this step)

breautek commented Jul 27, 2021

@LucasFebatis android version 10.0.1 (unreleased, pending votes) will fix the platform so that it will find the latest build tools release of a specific major rather than blindly choosing the latest available. Additionally the same version also fixes the flag (regression introduced in 10.0.0) so that if declared it will use a specific build tools version of your choice, as long as it’s >= our minimum build tools version.

You can give it a try by installing the nightly version. Note that Cordova android 9.x won’t be patched.

boredom2 commented Jul 31, 2021 •

Hi there.
After «cordova platform add android@10.0.1» and then «cordova build» (without any Plugins, just the Skeleton App), I still get «Failed to find Build Tools revision 31.0.0-rc5». What am I missing?

(before that message, I receive «Build-tool 31.0.0 rc5 is missing DX at C:\Users*\AppData\Local\Android\sdk\build-tools\31.0.0-rc5\dx.bat») Shouldnt the Fix only consider Build Tools from 30.* instead of 31?

dattakadiyala commented Aug 4, 2021 •

if any one using Azure devOps, Microsoft hosted macOS agents, adding this as a command-line task before the build should do
SDKMANAGER=$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager echo y | $SDKMANAGER —uninstall «build-tools;31.0.0»

breautek commented Aug 4, 2021

(before that message, I receive «Build-tool 31.0.0 rc5 is missing DX at C:\Users*\AppData\Local\Android\sdk\build-tools\31.0.0-rc5\dx.bat») Shouldnt the Fix only consider Build Tools from 30.* instead of 31?

cordova-android@10.0.1 does include a patch that does just that. I wonder if the pre-release label however is causing problems. This was tested against a production release version (e.g. version 31.0.0 ).

jaydrogers commented Aug 5, 2021 •

Just adding a note that I adopted @breautek’s work around from this comment: #1288 (comment)

His workaround pointed me in the right direction, but I needed to make a few changes.

The error I was seeing

What brought me to this thread was seeing this error message:

Then when I upgraded to 31.0.0, I realized that did not work either 😅

First, I had a different ENV var

I saw @breautek’s comment and noticed his variable was ANDROID_HOME , but mine was ANDROID_SDK_ROOT . Thankfully I noticed this in my logs:

So I changed the command to:

I then installed version 30.0.3:

Hope this helps as people smarter than me helps diagnose an actual solution 🤓

Thanks for your hard work!

pcwSlide commented Aug 7, 2021

The PR #1293 should provide a better workaround (by fixing the actual gradle arg parameter).

Hoping it will be reviewed and be included in our patch release.

Hey Norman,
I agree it needs to addressed correctly. I just removed the 31 sdk — works ok BUT- and yes — another 6 months has passed 🙂 — it does NOT invoke the emulator automatically — it has to be open to be seen by Cordova — an issue ( we — you ) finally fixed last round.. Do I open a new ticket for this?
Phil

NitzDKoder commented Aug 19, 2021

breautek commented Aug 19, 2021

The PR #1293 should provide a better workaround (by fixing the actual gradle arg parameter).
Hoping it will be reviewed and be included in our patch release.

Hey Norman,
I agree it needs to addressed correctly. I just removed the 31 sdk — works ok BUT- and yes — another 6 months has passed 🙂 — it does NOT invoke the emulator automatically — it has to be open to be seen by Cordova — an issue ( we — you ) finally fixed last round.. Do I open a new ticket for this?
Phil

Sorry for the late response. I’m not sure if I’m fully understanding your statement but Build Tools 31 requires breaking changes to be done on our end. I don’t think we need a new ticket for this, I think this ticket is sufficient is in our cordova-android@11 milestone so we can keep track of issues required to be resolved once cordova-android@11 development starts.

pcwSlide commented Aug 19, 2021

Yes Build 31 does not work — so I went back a version and it did compile but once again sending to the android emulator fails to engage — you have to manually open the emulator first — same old issue.

breautek commented Aug 19, 2021

Yes Build 31 does not work — so I went back a version and it did compile but once again sending to the android emulator fails to engage — you have to manually open the emulator first — same old issue.

Ok, emulator usage is definitely not related to this issue and should be reported as a separate ticket.

webb24h commented Aug 25, 2021

Just adding a note that I adopted @breautek’s work around from this comment: #1288 (comment)

His workaround pointed me in the right direction, but I needed to make a few changes.

The error I was seeing

What brought me to this thread was seeing this error message:

Then when I upgraded to 31.0.0, I realized that did not work either

First, I had a different ENV var

I saw @breautek’s comment and noticed his variable was ANDROID_HOME , but mine was ANDROID_SDK_ROOT . Thankfully I noticed this in my logs:

So I changed the command to:

I then installed version 30.0.3:

Hope this helps as people smarter than me helps diagnose an actual solution

Источник

Читайте также:  Смартфоны с новой версией андроид
Оцените статью