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 ?
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.
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.
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With