Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using thread annotation not being inspected as expected

I want to notify the developer that a method is required to be in the main thread so i wrote to following code :

  @MainThread
    public void showToast(@NonNull String text) {
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

than i wrote :

   new Thread(new Runnable() {
        @Override
        public void run() {
            showToast("");
        }
    }).start();

and the compiler not marking this as an error unlike @StringRes and others annotations that i used .

any idea why ?

like image 298
Jesus Dimrix Avatar asked Jun 19 '17 12:06

Jesus Dimrix


People also ask

What is@ NonNull in android?

public annotation NonNull. Denotes that a parameter, field or method return value can never be null. This is a marker annotation and it has no specific attributes.

How to use annotation class in android?

Add annotations to your project To enable annotations in your project, add the support-annotations dependency to your library or app. Any annotations you add then get checked when you run a code inspection or lint task.

How to add annotation in android Studio?

The first step is to build a new module that will house your annotations. Go to Android Studio and then click on File -> New ->New Module then choose Kotlin and after that, you need to add a name to the module like you usually do with your android projects. Name the module gfg-annotations. Set the package to com.


1 Answers

Supply your own annotations for thread inference

The lint inspection (aptly named "WrongThread") cannot infer the thread that is calling the showToast method unless you supply annotations that mark a method as one of @WorkerThread etc.

Take your original code and add the @WorkerThread annotation to the run method:

new Thread(new Runnable() {
    @Override
    @WorkerThread
    public void run() {
        showToast("");
    }
}).start();

and it will correctly generate the lint inspection warning as below:

lint inspection warning

Special case for AsyncTask

AsyncTask has its methods marked with the correct thread annotations (link to source):

@WorkerThread
protected abstract Result doInBackground(Params... params);

you will get the warning for free if you happen to use an AsyncTask like in the following example:

new AsyncTask<String, String, String>() {
    @Override
    protected String doInBackground(String... strings) {
        showToast(""); //warning here: method showToast must be called from the main thread
                       //currently inferred thread is worker
        return "";
    }

For other async patterns you will have to add your own @WorkerThread or other annotations.

The complete list of different threads is here:

@MainThread
@UiThread
@WorkerThread
@BinderThread
@AnyThread
like image 59
David Rawson Avatar answered Sep 20 '22 15:09

David Rawson