- Understanding deprecated in Android
- What is deprecation ?
- Is it wrong to use Deprecated methods or classes ?
- What happens if i continue using Deprecated methods?
- Conclusion :
- Android build fails due to deprecated ‘android’ command #743
- Comments
- kraxarn commented Apr 4, 2017 •
- goob256 commented Apr 4, 2017
- kraxarn commented Apr 4, 2017 •
- goob256 commented Apr 4, 2017
- kraxarn commented Apr 4, 2017 •
- goob256 commented Apr 4, 2017
- kraxarn commented Apr 4, 2017
- elias-pschernig commented Apr 4, 2017
- elias-pschernig commented Apr 4, 2017
- kraxarn commented Apr 4, 2017
- goob256 commented Apr 4, 2017
- goob256 commented Apr 4, 2017
- goob256 commented Apr 4, 2017
- goob256 commented Apr 4, 2017
- kraxarn commented Apr 4, 2017 •
- goob256 commented Apr 4, 2017
- goob256 commented Apr 4, 2017
- sjfricke commented Aug 21, 2017
- rayraysunrise commented Sep 5, 2017
- elias-pschernig commented Jan 11, 2018
- Android Building Backwards Compatible Apps How to handle deprecated API
- Example
- Easier alternative: Use the Support Library
- Kotlin Android Extensions deprecated. Что делать?Инструкция по миграции
- Кратко о Kotlin Android Extensions
- Проблемы Kotlin Android Extensions
- Альтернативные способы
- View Binding от Google
- Начало работы с View Binding
- Использование в Activity
- Android build fails with Android SDK Build-Tools 31.0.0 #1288
- Comments
- kputh commented Jul 21, 2021
- Bug Report
- Problem
- What is expected to happen?
- What does actually happen?
- Information
- Command or Code
- Environment, Platform, Device
- Version information
- Checklist
- kputh commented Jul 21, 2021 •
- Workaround
- breautek commented Jul 21, 2021 •
- miketimofeev commented Jul 23, 2021
- breautek commented Jul 23, 2021 •
- pawan-logiciel commented Jul 24, 2021
- kputh commented Jul 26, 2021
- kputh commented Jul 26, 2021
- breautek commented Jul 26, 2021
- breautek commented Jul 26, 2021
- LucasFebatis commented Jul 27, 2021
- breautek commented Jul 27, 2021
- boredom2 commented Jul 31, 2021 •
- dattakadiyala commented Aug 4, 2021 •
- breautek commented Aug 4, 2021
- jaydrogers commented Aug 5, 2021 •
- The error I was seeing
- First, I had a different ENV var
- So I changed the command to:
- I then installed version 30.0.3:
- pcwSlide commented Aug 7, 2021
- NitzDKoder commented Aug 19, 2021
- breautek commented Aug 19, 2021
- pcwSlide commented Aug 19, 2021
- breautek commented Aug 19, 2021
- webb24h commented Aug 25, 2021
- The error I was seeing
- First, I had a different ENV var
- So I changed the command to:
- I then installed version 30.0.3:
Understanding deprecated in Android
Google releases new versions of android with a year cycle. In process of which developers write some more useful API, methods, classes which are powerful than existing one. So they encourage developers to use newly written API’s and depricate old methods.
What is deprecation ?
- In Android deprecation usually means “ We will continue to support this, but we think there are better solutions”.
- Most of the time features are deprecated rather than immediately removed, to provide backward compatibility, and to give programmers time to bring affected code into compliance with the new standard.
Is it wrong to use Deprecated methods or classes ?
- The main disadvantage is that the API might not be available in future versions, which will increase the cost of updating your application.
- If the deprecated method is easy to replace, use the replacement. If it isn’t, it’s up to you to decide whether developing the “future-proof” way is worth the additional effort.
- setBackgroundDrawable can easily be replaced by setDrawable see in detail here.
- On the other hand, startManagingCursoris much harder to replace, so one might put off transitioning to ContentProvider until there is no other option.
What happens if i continue using Deprecated methods?
- Code would continue running as it is until method is removed from SDK. If you are using deprecated method then you must keep track of removed apis whenever you upgrade to newest SDK.
- If you don’t want a change at all then check for the reason behind deprecation. If deprecation is because of performance issues then you might consider upgrading to newest methods.
Conclusion :
By researching why a method is deprecated I often learn interesting things about SDK and different ways of doing same thing. There is often a good reason behind deprecation which leads to better understanding of the Android SDK. So from a learning/growing perspective, it is also a worthwhile effort.
I learned about VibrationEffect class while looking at ‘deprecated’ tag on .vibrate() method. Here is my learning :
Источник
Android build fails due to deprecated ‘android’ command #743
Comments
kraxarn commented Apr 4, 2017 •
The new Android SDK deprecates the ‘android’ command and the SDK manager, moving everything to Android Studio. This makes the final ‘make’ compile fail with the following error:
The text was updated successfully, but these errors were encountered:
goob256 commented Apr 4, 2017
What version of the sdk do you have? I know it’s been deprecated but I just recently did a clean install and it works. To get the sdk manager you can use «android sdk» command. But you may be right, maybe they took it a step further (grumble grumble google changes things every 2 days it seems. )
kraxarn commented Apr 4, 2017 •
Downloaded and installed it just now through Android Studio.
Seems like if you already have the SDK manager, it doesn’t get removed when updating.
goob256 commented Apr 4, 2017
I guess you’re right. The build system will need to be updated to gradle. Until then, maybe try getting an older sdk. Elias said he wanted to update to gradle so maybe he’ll do it.
kraxarn commented Apr 4, 2017 •
Now I get this error instead
goob256 commented Apr 4, 2017
How are you building? Looks like you’re trying to target Android 1.5 while Allegro only supports 2.3 (version 9) and up.
kraxarn commented Apr 4, 2017
getRectSize was added in API 13, while Allegro suggests you use API 12. Looks like an issue there
elias-pschernig commented Apr 4, 2017
You can always use the pre-compiled binaries for Android as well, just in case you missed those. You can also look at the script to create those binaries to get an idea how it can be done (they are command-line only without any Android Studio).
elias-pschernig commented Apr 4, 2017
Oh, I use API 15 for those binaries, so yes, if you need to support older they won’t work of course.
kraxarn commented Apr 4, 2017
I’ll try recompiling for API 19 instead, but if that’s the issue, you may want to update the guide :p
goob256 commented Apr 4, 2017
The source file checks the Android version so it’s not an issue. I build with API 9 and it works fine.
goob256 commented Apr 4, 2017
What you need to do is build with the latest SDK but set your minimum target to Android 9.
goob256 commented Apr 4, 2017
Here’s what I have in my manifest:
goob256 commented Apr 4, 2017
You can use 25 or 24 or whatever is the latest.
kraxarn commented Apr 4, 2017 •
Compiled fine when setting API to 19, so might want to change that in the guide.
I do get this error still though, but seems to compile fine and it says BUILD SUCCESSFUL, no not really sure error: cannot find -lstlport_shared
goob256 commented Apr 4, 2017
That’s something else that should be removed from the guide. it’s unnecessary.
goob256 commented Apr 4, 2017
Patches are welcome btw.
sjfricke commented Aug 21, 2017
I have searched and found no replacement for the android update project command.
If you still need to build I suggest reverting to SDK Tools 25.2.5 or earlier as they removed the command in Build Tool 25.3.0
rayraysunrise commented Sep 5, 2017
@sjfricke This fixes cocos2d-x issues too, thanks dude!
elias-pschernig commented Jan 11, 2018
Should be fixed by commit 55184a.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Android Building Backwards Compatible Apps How to handle deprecated API
Example
It is unlikely for a developer to not come across a deprecated API during a development process. A deprecated program element is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers and analyzers (like LINT) warn when a deprecated program element is used or overridden in non-deprecated code.
A deprecated API is usually identified in Android Studio using a strikeout. In the example below, the method .getColor(int id) is deprecated:
If possible, developers are encouraged to use alternative APIs and elements. It is possible to check backwards compatibility of a library by visiting the Android documentation for the library and checking the «Added in API level x» section:
In the case that the API you need to use is not compatible with the Android version that your users are using, you should check for the API level of the user before using that library. For example:
Using this method ensures that your app will remain compatible with new Android versions as well as existing versions.
Easier alternative: Use the Support Library
If the Support Libraries are used, often there are static helper methods to accomplish the same task with less client code. Instead of the if/else block above, just use:
Most deprecated methods that have newer methods with a different signature and many new features that may not have been able to be used on older versions have compatibility helper methods like this. To find others, browse through the support library for classes like ContextCompat , ViewCompat , etc.
Источник
Kotlin Android Extensions deprecated. Что делать?Инструкция по миграции
Возможно, вы уже слышали, что Kotlin Android Extensions — плагин для Kotlin теперь deprecated.
kotlinx.android.synthetic is no longer a recommended practice. Removing in favour of explicit findViewById
Безусловно, это было очень удобно, особенно если у вас проект полностью на Kotlin. Однако, мир меняется и теперь нужно искать альтернативы. В этой статье мы кратко рассмотрим, что такое плагин Kotlin Android Extension, какие были проблемы с ним и что теперь нам, Android-разработчикам делать. Частично, использовался материал этой статьи. Итак, поехали.
Кратко о Kotlin Android Extensions
Kotlin Android Extensions — это плагин для Kotlin, позволяющий восстанавливать view из Activities, Fragments, и Views без написания стандартного бойлерплэйт-кода типа findViewById.
Плагин генерирует дополнительный код, который позволяет получить доступ к view в виде XML, так же, как если бы вы имели дело с properties с именем id, который вы использовали при определении структуры.
Также он создаёт локальный кэш view. При первом использовании свойства, плагин выполнит стандартный findViewById. В последующем, view будет восстановлен из кэша, поэтому доступ к нему будет быстрее.
Если это всё так удобно, то зачем его сделали deprecated?
Проблемы Kotlin Android Extensions
- Используется глобальный нэйминг идентификаторов. Могут возникнуть ситуации, когда один и тот же идентификатор имеется у разных view в разных лэйаутах — соответственно только на этапе работы приложения вы узнаете о том, что использовали не тот id.
- Возможно использовать только в проектах на Kotlin (кэп)
- Отсутствует Null Safety. В случае, когда view представлена в одной конфигурации и отсутствует в другой — может возникнуть краш, т.к отсутствует обработка таких ситуаций
- Невозможно использовать в многомодульных проектах. Очень распространённый сценарий: у вас есть модуль UI Kit, хранящий общие UI-компоненты, которые вы хотите переиспользовать в других модулях. До сих пор висит issues которое вряд ли поправят. В таком сценарии обычно используют старый добрый findViewById 🙁
- Резюмируя приведённые недостатки, нетрудно понять, что этот подход не идеален — хотя, безусловно, очень удобен на небольших проектах. На больших проектах с многомодульной архитектурой и сотнями экранов — использование Kotlin Android Extensions уже не кажется идеальным решением.
Альтернативные способы
- Использование KotterKnife (кек, даже не думайте).
- Старый добрый FindViewById() — уже получше, но так себе.
- Использование AndroidAnnotations (привет из 2015)
- View Binding от Google — бинго!
View Binding от Google
Итак, победителем в этом списке выглядит ViewBinding от Google (не путайте с DataBinding). Давайте кратко рассмотрим, что это такое.
View Binding — это инструмент, который позволяет проще писать код для взаимодействия с view. При включении View Binding в определенном модуле он генерирует binding классы для каждого файла разметки (layout) в модуле. Объект сгенерированного binding класса содержит ссылки на все view из файла разметки, для которых указан android:id
Главные преимущества View Binding — это Null safety и Type safety.
Начало работы с View Binding
Начать работать с ViewBinding достаточно просто. Нужно добавить опцию в build.gradle:
После этого можно уже использовать.
Каждый сгенерированный binding класс содержит ссылку на корневой view разметки ( root ) и ссылки на все view, которые имеют id. Имя генерируемого класса формируется как «название файла разметки», переведенное в camel case + «Binding».
Например, для файла разметки result_profile.xml :
Будет сгенерирован класс ResultProfileBinding , содержащий 2 поля: TextView name и Button button .
Использование в Activity
Например у вас вот такой layout:
Результат работы ViewBinding:
Использовать viewBinding можно так:
И теперь, после того, как получили ссылки на view:
Если вы используете ViewBinding во фрагменте и держите ссылку на binding во фрагменте (а не только в методе onCreateView()) то не забывайте очищать ссылки в методе onDestroyView(). Пример:
Это необходимо делать из-за жизненного цикла фрагмента и view:
В целом, переключиться на ViewBinding достаточно не сложно, хотя и жаль, что Kotlin Android Extensions объявлен deprecated. А я напоминаю, что на практическом онлайн-интенсиве по Android-разработке -вы можете быстро освоить современную Android-разработку с наставником.
Подписывайся на канал чтобы не пропустить анонс и хлопай внизу если статья был полезная.
Понравилась статья? Не забудь подписаться и поставить лайк, а ещё
Источник
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
Источник