deprecated warning while compiling - android

i have a question regarding development environments settings.
i am trying to see if there is any possibility to make a compilation warning in a development environment(eclipse,android studio)for android applications using a deprecated feature(could be a method , constructor or whatever you can think of ). until now i am working manually to find the use of this deprecated features , and my boss asked me to look for an automatic settings in my idea ...
so lets say for a specific code :
protected void onPrepareDialog(int paramInt, Dialog paramDialog)
{
try
{
super.onPrepareDialog(paramInt, paramDialog);
AlertDialog localAlertDialog = (AlertDialog)paramDialog;
localAlertDialog.setTitle("Passphrase required");
((TextView)localAlertDialog.findViewById(2131230727)).setText(Preferences.getConfigName(this, getConfigFile()));
Button localButton = localAlertDialog.getButton(-3);
if (this.mOpenVpnService != null);
for (boolean bool = true; ; bool = false)
{
localButton.setEnabled(bool);
return;
}
i have several deprecated features here , and android studio declares it , but what i need is a configuration for this warning to be automated and save me the need of walking through each class manually ...

Select Analyze > Inspect Code to run lint on your project. It should detect any deprecated methods, as well as others common mistakes in your project.
You can select "Run inspection by name" and there you can find "Deprecated API usage" (Java / Code maturity issues).

For me the best solution is add this lines in the file build.gradle(project:appname)
allprojects {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
Then all the deprecated methods in the java files appear in the build tab:
deprecated api tab android studio
This works on gradle 5.1.1

Related

Is it possible to get dependency version at runtime, including from library itself?

Background
Suppose I make an Android library called "MySdk", and I publish it on Jitpack/Maven.
The user of the SDK would use it by adding just the dependency of :
implementation 'com.github.my-sdk:MySdk:1.0.1'
What I'd like to get is the "1.0.1" part from it, whether I do it from within the Android library itself (can be useful to send to the SDK-server which version is used), or from the app that uses it (can be useful to report about specific issues, including via Crashlytics).
The problem
I can't find any reflection or gradle task to reach it.
What I've tried
Searching about it, if I indeed work on the Android library (that is used as a dependency), all I've found is that I can manage the version myself, via code.
Some said I could use BuildConfig of the package name of the library, but then it means that if I forget to update the code a moment before I publish the dependency, it will use the wrong value. Example of using this method:
plugins {
...
}
final def sdkVersion = "1.0.22"
android {
...
buildTypes {
release {
...
buildConfigField "String", "SDK_VERSION", "\"" + sdkVersion + "\""
}
debug {
buildConfigField "String", "SDK_VERSION", "\"" + sdkVersion + "-unreleased\""
}
}
Usage is just checking the value of BuildConfig.SDK_VERSION (after building).
Another possible solution is perhaps from gradle task inside the Android-library, that would be forced to be launched whenever you build the app that uses this library. However, I've failed to find how do it (found something here)
The question
Is it possible to query the dependency version from within the Android library of the dependency (and from the app that uses it, of course), so that I could use it during runtime?
Something automatic, that won't require me to update it before publishing ?
Maybe using Gradle task that is defined in the library, and forced to be used when building the app that uses the library?
You can use a Gradle task to capture the version of the library as presented in the build.gradle dependencies and store the version information in BuildConfig.java for each build type.
The task below captures the version of the "appcompat" dependency as an example.
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.0'
}
task CaptureLibraryVersion {
def libDef = project.configurations.getByName('implementation').allDependencies.matching {
it.group.equals("androidx.appcompat") && it.name.equals("appcompat")
}
if (libDef.size() > 0) {
android.buildTypes.each {
it.buildConfigField 'String', 'LIB_VERSION', "\"${libDef[0].version}\""
}
}
}
For my example, the "appcompat" version was 1.4.0. After the task is run, BuildConfig.java contains
// Field from build type: debug
public static final String LIB_VERSION = "1.4.0";
You can reference this field in code with BuildConfig.LIB_VERSION. The task can be automatically run during each build cycle.
The simple answer to your question is 'yes' - you can do it. But if you want a simple solution to do it so the answer transforms to 'no' - there is no simple solution.
The libraries are in the classpath of your package, thus the only way to access their info at the runtime would be to record needed information during the compilation time and expose it to your application at the runtime.
There are two major 'correct' ways and you kinda have described them in your question but I will elaborate a bit.
The most correct way and relatively easy way is to expose all those variables as BuildConfig or String res values via gradle pretty much as described here. You can try to generify the approach for this using local-prefs(or helper gradle file) to store versions and use them everywhere it is needed. More info here, here, and here
The second correct, but much more complicated way is to write a gradle plugin or at least some set of tasks for collecting needed values during compile-time and providing an interface(usually via your app assets or res) for your app to access them during runtime. A pretty similar thing is already implemented for google libraries in Google Play services Plugins so it would be a good place to start.
All the other possible implementations are variations of the described two or their combination.
You can create buildSrc folder and manage dependencies in there.
after that, you can import & use Versions class in anywhere of your app.

Testing inconvenience: Android Studio JUnit vs Gradle based: testOptions ignored by Android Studio

The following was done with Android Studio 3.4, Android Gradle Plugin 3.3.2 and Gradle 4.10.3.
In the build.gradle file, I have configured some unit test options like this:
android {
testOptions {
unitTests.all {
systemProperty "debug","true"
}
}
}
I do have a test function that tries to read this property:
package com.demo;
public class SysPropTestDemo {
#Test
public static void dumpSysProps() {
System.out.println("sysprop(debug)=" + System.getProperty("debug"));
}
}
When run via command line gradlew test --test com.demo.SysPropTestDemo I will get the property debug set correctly to true. If I run the same test via Android Studio without setting any options, the value shown will be null.
In order to get the same result from Android Studio, I explicitly have to enter some values in the "Run/Debug Configurations" panel, i.e something like -Ddebug=true in the VM options.
Now this is a trivial example, but what I really want to do, is to add some path to the java.library.path property in order to be able to load a JNI library compiled within the project. (I do need to write some tests that make use a modified SQLite lib, so not using JNI is not an option here)
It does work when setting additional options, but I think this is very inconvenient, since I can't enter a variable based value in the configuration options (or at least, I don't know how to). To sum it up: when setting or changing values, I do have to go through a bunch of config screens where I would really prefer to have one place in a config file.
Shouldn't Android Studio somehow make use of the values specified in the build.gradle file? If not, the docs don't make it clear that the testOptions.unitTests.all settings can only be used via gradlew invocation.
Skybow,
I feel you have two questions
1. How to load jni lib for androidTest(not for 'test[non instrumented unit tests])
- copy your jni library in corresponding folder [JNI libraries: [app/src/androidTestFLAVORNAMEDebug/jniLibs]
- load your jni library
static {
try {
System.loadLibrary("xyzjni");
} catch (Exception e) {
Logger.error("Exception on loading the jni library : " + e.getMessage());
}
}
2. How to make android studio use your config variables defined for unitTests.
- It would have great if some text file is there which has all configs.
- Or it is part of build.gradle
- I don't have any detail on this.

How to resolve "Obsolete custom lint check" for my custom IssueRegistry written in Kotlin and make it work (Android)

I am trying to implement custom lint checks (using Kotlin). I have set up a module for my custom checks and added classes to test my first lew lint check, mostly following these two tutorials here and here.
So I now have a module, I have a custom IssueRegistry, I've created an issue and a Detector class for it. So far it seems complete. I've added a test to check if my lint check works and it looks alright.
I have added my module to the project by referencing it in settings.gradle like this: include ':app', ':somemodule', ':mylintmodule'
Now if I run the linter using ./gradlew lint I get a lint result file telling me this:
Lint found an issue registry (com.myproject.mylintmodule) which requires a newer API level. That means that the custom lint checks are intended for a newer lint version; please upgrade
Lint can be extended with "custom checks": additional checks implemented by developers and libraries to for example enforce specific API usages required by a library or a company coding style guideline.
The Lint APIs are not yet stable, so these checks may either cause a performance degradation, or stop working, or provide wrong results.
This warning flags custom lint checks that are found to be using obsolete APIs and will need to be updated to run in the current lint environment.
It may also flag issues found to be using a newer version of the API, meaning that you need to use a newer version of lint (or Android Studio or Gradle plugin etc) to work with these checks.
To suppress this error, use the issue id "ObsoleteLintCustomCheck" as explained in the Suppressing Warnings and Errors section.
So it tells me that I am using a newer API verion in my custom lint check, right? This is my custom IssueRegistry (minus some parts not relevant for this problem):
class MyCustomIssueRegistry : IssueRegistry() {
override val issues: List<Issue>
get() = listOf(ISSUE_NAMING_PATTERN)
override val api: Int = com.android.tools.lint.detector.api.CURRENT_API
override val minApi: Int = 1
}
From googling this problem and finding this issue I figured I have to override and set the right API version (and maybe the min API?) by overriding these properties like I did above (this version is my last attempt, directly taken from that issue).
So this property can be set to values between -1 and 5, meaning this (taken right out of the lint.detector.api class):
/** Describes the given API level */
fun describeApi(api: Int): String {
return when (api) {
5 -> "3.5+" // 3.5.0-alpha07
4 -> "3.4" // 3.4.0-alpha03
3 -> "3.3" // 3.3.0-alpha12
2 -> "3.2" // 3.2.0-alpha07
1 -> "3.1" // Initial; 3.1.0-alpha4
0 -> "3.0 and older"
-1 -> "Not specified"
else -> "Future: $api"
}
I have tried all of them, plus the one above adding a minApi override too, and I keep getting the exact same result for each of them.
Also I am unable to locate what other API version this is compared with. Is there a place where this is set for the regular linter in an Android project?
It's also unclear to me what I have to do to make sure my changes got applied - is it enough to change some code, then run lint, or do I have to compile the project first, or build & clean?
Following the tutorials, I added my custom lint check by adding this to the app's build.gradle: lintChecks project(":mylintmodule")
Is that even right? The API issue on my registry class shows up no matter if my lint check is referenced (and hopefully used) like that or not. I have also tried the other method described in the first tutorial, adding this task to the linter module build.gradle:
defaultTasks 'assemble'
task copyLintJar(type: Copy) {
description = 'Copies the lint jar file into the {user.home}/.android/lint folder.'
from('build/libs/')
into(System.getProperty("user.home") + '/.android/lint')
include("*.jar")
}
// Runs the copyLintJar task after build has completed.
build.finalizedBy(copyLintJar)
But since I can't figure out how to see if my custom checks are actually run, I don't know if that works as intended either.
So how do I get this warning resolved (since I interpret the text as "As long as the versions don't match I will not try to run your lint check"), and how can I make sure my lint check is actually run by the linter?

Getting the Android SDK directory within a gradle task

Recently the gradle plugin for android got updated (with android studio), after which the previous way of getting to the SDK directory ceased to work. The expression
${android.plugin.sdkDirectory}
which worked in an older version now returns the error
Error:(42, 0) No such property: sdkDirectory for class: com.android.build.gradle.LibraryPlugin
What would be the proper way of getting the android SDK directory being used, preferably independent of the user's configuration such as plugin and gradle version? The script needs to be shareable with several users.
Since all the previous answers depend on the environment or specific user intervention on top of normal configuration, I'll just post my technically messy fix.
if (android.hasProperty('plugin')) {
if (android.plugin.hasProperty('sdkHandler')) {
androidPath = android.plugin.sdkHandler.sdkFolder
} else {
androidPath = android.plugin.sdkDirectory
}
} else {
androidPath = android.sdkDirectory
}
Unlike all previous methods, this actually works, but it still looks hacky.
In gradle.properties set location sdkdir=/home/user/android-sdk and then in gradle you can use $sdkdir
I'm using Android gradle plugin v1.2.3 and this works fine:
${android.sdkDirectory}
You can use
$System.env.ANDROID_HOME
export ANDROID_HOME=/xxx/xxx/ in shell, then use it by System.env.ANDROID_HOME in gradle file.

How to suppress specific Lint warning for deprecated Android function?

I use a version switch to support older Android versions.
int sdk = Build.VERSION.SDK_INT;
if (sdk < Build.VERSION_CODES.HONEYCOMB) {
ColorDrawable colorDrawable = new ColorDrawable(shapeColor);
//noinspection deprecation
viewHolder.shape.setBackgroundDrawable(colorDrawable);
} else {
viewHolder.shape.setColor(shapeColor);
}
When build the project with Gradle from the command line the following warning is output by Lint:
app/src/main/java/com/example/MyApp/CustomListAdapter.java:92: warning:
[deprecation] setBackgroundDrawable(Drawable) in View has been deprecated
viewHolder.shape.setBackgroundDrawable(colorDrawable);
^
Can I annotate the specific line or method to mute the warning (since I do it on purpose)? I do not want to disable all warnings.
Case is important, use the following either inline or class-wide:
#Suppress("DEPRECATION")
This is in Kotlin.
I've noticed that the #SuppressLint("deprecated") inline annotation won't be picked up anymore - while #SuppressWarnings("deprecation") is being picked up.
one can disable the Deprecation checks for the Gradle linter with lintOptions within the module-level build.gradle file; while there is no chance to define individual files like that:
android {
lintOptions {
disable 'Deprecation'
}
}
or on can assign one rather detailed lint.xml configuration file with LintOptions:lintConfig (when settings showAll true, it will still show the warnings - no matter the provided XML configuration):
android {
lintOptions {
lintConfig file("lint.xml")
showAll false
}
}
where one can add individual files, by adding their paths:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="Deprecation" severity="Error">
<ignore path="app/src/main/java/com/example/MyApp/CustomListAdapter.java" />
</issue>
</lint>
The source code of com.android.builder.model.LintOptions might explain, what actually happens there (and confirms about 50% of what I've wrote).
in order to get rid of the inline warnings in Android Studio... that linter appears to be another linter - and these annotations do not affect the linter of the Gradle build (it may be required to use this combined with one of the methods stated above, in order to ignore known deprecated classes and methods):
//noinspection deprecation
update The Android Studio 2.3 release notes mention a new feature:
Lint Baseline: With Android Studio 2.3, you can set unresolved lint warnings as a baseline in your project. From that point forward, Lint will report only new issues. This is helpful if you have many legacy lint issues in your app, but just want to focus on fixing new issues. Learn more about Lint baseline and the new Lint checks & annotations added in this release.
here it's explained, how to create a Lint warnings baseline - which records the detected warnings into an XML file and then mutes them (which is way better than to have the code annotations inline, distributed all over the place); I'd assume, that options lintConfig and baseline should be combine-able (depending on the requirements).
android {
lintOptions {
baseline file("lint-baseline.xml")
}
}
Just something new: Not sure about Android Studio, but, to remove this warning from this line, you can use:
//noinspection deprecation
This removes the warning from the next line.
E.g:
//noinspection deprecation
e.setBackgroundDrawable(editTextDrawable);
It won't show an error. However, as #JJD said, this still outputs the warning to the console. But at least you can have a nice error-less code which can be useful like for Git for example. And, this prevents the problem with #SupressWarnings, which is it ignores all warnings in the method. So if you have something deprecated that you are not aware of, #SupressWarnings will hide it and you will not be warned. That is the advantage of the //noinspection
I ran into a similar problem. First I got a compiler warning:
:compileDebugJava
Note: /path/file.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Which you can suppress with #SuppressWarnings("deprecation") or just ignore since it is a warning and does cause your build to fail.
Additionally I got the lint error (details in build/lint-results.html):
Call requires API level 13 (current min is 9)
This could be suppressed by adding #SuppressLint("NewApi"). Alternatively you could use #TargetApi(13) to hint that the method/class may use methods that depend on API version 13, rather than what you have set as minSdkVersion (e.g. 9).
The annotations can only be done at a class or function level, not for a single line. Also note that "deprecation" should not be capitalized, while that didn't seem to matter for "NewApi".
To avoid lint warnings, always split functions so one function deals with the old system and other one deals with the new system. The old can supress the warning safely. The new one should be annotated to be used only on newest api levels.
This is an example on how it should look:
#SuppressWarnings("deprecation")
private static int getVersionCode_old(#NonNull Context appContext) {
PackageInfo pInfo;
try {
pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
return pInfo.versionCode;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
#RequiresApi(api = Build.VERSION_CODES.P)
private static int getVersionCode_new(#NonNull Context appContext) {
PackageInfo pInfo ;
try {
pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
return (int) pInfo.getLongVersionCode();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public static int getVersionCodeUniversal(#NonNull Context appContext)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return getVersionCode_new(appContext);
}
else
{
return getVersionCode_old(appContext);
}
}
Another important hint to avoid lint warnings: if you are using a whole deprecated class then you should remove all explicit imports for that class. Then just access to that class directly using its full path, and only do it in the old versions of your functions.
And finally, you should consider start using androidX, the new Google libraries where you will find a lot of universal functions ready to use. Then you can save a lot of time with this kind of small problems. For example, you can remove all the code of the above example and simply use this new and universal androidX function:
PackageInfo.getLongVersionCode()
You need to create a lint.xml file to tell lint what to ignore.
http://tools.android.com/tips/lint/suppressing-lint-warnings see this for more details
yours might look a little like this
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- Disable the given check in this project -->
<issue id="Deprecation">
<ignore path="app/src/main/java/com/example/MyApp/CustomListAdapter.java" />
</issue>
</lint>
To handle this in the source you should use something like
#SuppressLint("Deprecation")
Just use #SuppressWarnings("deprecation") above the function to suppress that specific warning for that function only.
Works like a charm!
#Blackd has the better answer. You should accept that!
Try to find a method from ViewCompat to replace the deprecated method.
In your case, use ViewCompat.setBackground(View, Drawable).
There are many classes named XXXCompat for cases like that, such as ContextCompat, ActivityCompat and so on.

Categories

Resources