Jesus Dimrix
Jesus Dimrix

Reputation: 4568

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 ?

Upvotes: 11

Views: 2662

Answers (1)

David Rawson
David Rawson

Reputation: 21417

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

Upvotes: 9

Related Questions