Waiting for a specific operation - Android

Amirhossein Esmaeeili :

I want to wait for a specific operation to complete before continuing the code flow. Something like this:

protected void onCreate(Bundle savedInstanceState) {

downloadSomeFiles(); // I want to wait for this operation to finish
Log.d("Download", "Download Complete") //This should run After downloading completed
}

However downloading takes some time and I always end up getting NullPointerException because downloading wasn't completed. Assume we don't know how long we must wait.

Halex :

Long running operations on the main thread are never a good idea, as they block the User Interface.

If you want to do this while the application is running, consider using methods from java.util.concurrent package (or coroutines if you want to switch to Kotlin). AsyncTask became deprecated. Here is a guide: https://www.baeldung.com/java-concurrency

If you want your download to execute in the background even if your application is closed, consider using a Service: https://developer.android.com/guide/components/services

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400313&siteId=1