0

I tried to go through the documentation the android provides about AsyncTask, even though it's a bit too much to comprehend, but what I came across is Threading rules for AsyncTask to work properly.

I paste the link here; https://developer.android.com/reference/android/os/AsyncTask.html#threading-rules

Here are the rules;

There are a few threading rules that must be followed for this class to work properly:

  1. The AsyncTask class must be loaded on the UI thread. This is done automatically as of Build.VERSION_CODES.JELLY_BEAN.

  2. The task instance must be created on the UI thread.

  3. execute(Params...) must be invoked on the UI thread.

  4. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

  5. The task can be executed only once (an exception will be thrown if a second execution i is attempted.)

I understand the rule 2, 3, and 4 also.

What I don't understand is the rule 1 and 5.

The class that extends AsyncTask is the instance created on the UI thread (for example onCreate()) - rule 2

What they are trying to say in rule 1?
How it is loaded automatically without we ever mention it?

As of rule 5, are they saying, a single instance of the class that extends AsyncTask can be executed once, if we want to execute one more time, do we have to create another instance of the same class?

Thanks

  • If you're stuck on Java, [here's an alternative to AsyncTask](https://stackoverflow.com/a/58767934/7434090). You shouldn't be using AsyncTask any more. – Gavin Wright Sep 03 '21 at 03:41

1 Answers1

0

The entire class is deprecated, you shouldn't be using it anymore anyway.

Rule 5 means that a single instance of an AsyncTask can only be run once. You need to create another instance to run it again.

Rule 1 is about loading the Java Class object for the class. This happens automatically when needed and happens once per execution of the app. This is something you don't really need to worry about unless you're doing something weird.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • "This happens automatically when needed and happens once per execution of the app".What is meant by that, when needed and happens? – mockingbird Sep 03 '21 at 03:51
  • The class file is loaded from the dex file into memory so the JVM can use it. This is done via the class loader, which is done for you behind the scenes by default (you can customize this if needed). Unless you're getting really into the weeds about how the JVM works, don't worry about it. – Gabe Sechan Sep 03 '21 at 03:53