Android use deprecated api

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.

Читайте также:  Android linearlayout space between items

I learned about VibrationEffect class while looking at ‘deprecated’ tag on .vibrate() method. Here is my learning :

Источник

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.

Источник

Deprecated API Android #223

Comments

LukePenkava commented Oct 7, 2019

React Native version: 0.61.2
RNC-Async-Storage version: 1.6.2
Platform: Android, Android studio 3.4.2

Current behavior

Building in Android studio throws this Java compiler information. Not sure how big deal it is.

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

Krizzu commented Oct 7, 2019

@LukePenkava From my research — not a big deal for now.

Andriiklymiuk commented Oct 7, 2019 •

This prevents from building the app, how it can be fixed?
Edit: fixed my issue, so no worry

Krizzu commented Oct 7, 2019

@Andriiklymiuk but this is a warning, right? Warnings won’t stop your build

Andriiklymiuk commented Oct 7, 2019

@Krizzu well, in my case it was plain crash, but it somehow disappeared after project cleanup.
So yes, it is not big deal

Kamill90 commented Oct 8, 2019 •

@Krizzu What if it doesn’t disappear and disables building APK?
gradlew cleaned, caches invalidated, restarted, Android Studio upgraded.

tomhallam commented Oct 11, 2019

@Krizzu well, in my case it was plain crash, but it somehow disappeared after project cleanup.
So yes, it is not big deal

What did you do to clean your project up? I am struggling with errors from a number of libraries which means that the app cannot be packaged.

Читайте также:  Android 11 список устройств honor дата выхода

Krizzu commented Oct 11, 2019

I’d need an error message that actually says the cause the crash.
Warnings do not prevent your package to be build

tomhallam commented Oct 11, 2019 •

@Krizzu, ultimately the failure is:

Type com.google.android.gms.common.internal.zzf is referenced as an interface from com.google.android.gms.internal.zzcku .

There appear to be deprecated APIs in a couple of my dependencies, but as you say I don’t believe these warnings are causing the build to fail. But something is!

From Android Studio:

James-E-Adams commented Oct 21, 2019

In the same boat trying to upgrade React Native from 0.59 -> ^0.61. Have tried async-storage on v1.3.3 and v1.6.2 but getting this error and can’t build on Android. Anyone come up with a temp solution?

Krizzu commented Oct 22, 2019 •

@tomhallam @James-E-Adams Are you using firebase by any chance?

Among the others, Async Storage warnings showing up in your console is a misleading hint of an actual cause.

There might be a clash of dependencies, like mixing of androidx and support libraries . One (or more) of your dependencies can cause this mixing.

I suggest to try to build your app with minimal dependencies you can get and slowly start adding them up, one by one, to see where the crash comes from.

maxKimoby commented Oct 22, 2019 •

  • Delete node_modules
  • run npm install or yarn
  • run npx jetify

Do you still have the issue?

Edit: Command is npx jetify and not jetifier as I first wrote.

Malikkhoja-zz commented Oct 24, 2019 •

In the case of release build on 0.61.2, how should we run jetifier?

maxKimoby commented Oct 24, 2019 •

I believe when you run npx jetify it parses all your node_modules and changes the deprecated imports to remove support libraries. When running react-native run android (development mode), it calls jetifier by default. So I think you have to run jetifier at the root of your project so it can modify the deprecated imports in your node_modules and then build your app for release.

You should see this line:

Jetifier found 1353 file(s) to forward-jetify. Using 4 workers.

Edit: The command is npx jetify , my bad

ste001 commented Nov 12, 2019

I know this issue is closed, but I’m encountering the same exact issue as @LukePenkava, even the behaviour is the same.

I tried @maxKimoby solution, but it didn’t solve it, I still got the same error on AsyncStorageModule.java .

The problem is, it’s not a warning, it’s an error that prevents me from building the app.

carmelocatalfamo commented Nov 13, 2019 •

@ste001 same error here but for me npx jetify it works.
I have this command on postinstall script but seems not work after npm install or yarn install
It works running manual

Источник

deprecated API — что это ?

При компиляции чужого класса появляется следующее сообщение

Note: I:LanguageJavaJCreator LEMyProjectsdfConnectManager.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

Что такое deprecated API и чем мне это грозит ?

j2me что это и с чем это едят
На сколько я понимаю это язык на котором пишут для сотовых/. Как компилить то что написал Да и.

Ошибка при компиляции JAVA. error: ‘;’ expected Что это и как это исправить?
Добрый день. В первый раз в жизни пытаюсь скомпилировать примитивную программу Example.java, но.

Что это SMS HTTP API или что-то другое?
Доброго дня! Получил с сайта mlsit.ru готовую програмку для отправки смс с сайта. Который день.

Ошибка Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future
Пытаюсь создать сайт: Но при создании магаза открывается ошибка: Deprecated: mysql_connect(): The.

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli o
Здравствуйте! Сделал пример http://devcolibri.com/1486 со сборкой денвер сделал все в порядке.

Скрипт выдает ошибку: Deprecated: Function ereg() is deprecated
Вот я хотел установить почтовый дятел и Мой скрип выдает такие ошибки: Deprecated: Function.

Источник

Kotlin Android Extensions deprecated. Что делать? Инструкция по миграции

kotlinx.android.synthetic is no longer a recommended practice. Removing in favour of explicit findViewById

Кратко о Kotlin Android Extensions

Kotlin Android Extensions — это плагин для Kotlin, позволяющий восстанавливать view из Activities, Fragments, и Views без написания стандартного бойлерплэйт-кода типа findViewById.
Плагин генерирует дополнительный код, который позволяет получить доступ к view в виде XML, так же, как если бы вы имели дело с properties с именем id, который вы использовали при определении структуры.

Также он создаёт локальный кэш view. При первом использовании свойства, плагин выполнит стандартный findViewById. В последующем, view будет восстановлен из кэша, поэтому доступ к нему будет быстрее.

Если это всё так удобно, то зачем его сделали deprecated?

Проблемы Kotlin Android Extensions

Альтернативные способы

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:

Источник

Читайте также:  Stardew valley андроид управление
Оцените статью