Boardy
Boardy

Reputation: 36205

Stopping a thread in Android is deprecated

I am working on an Android project and I have a thread which is posting to a PHP API and does checks with the response.

Before the thread starts I show a progress dialog which can be cancelled. When the cancel is pressed I call thread.stop() but this shows up as deprecated.

Everything I have found on Google suggest that I have a flag and check the flag within the while loop and come out of the thread cleanly, however in my circumstances there is no loop, so how should I go about doing this?

Upvotes: 1

Views: 465

Answers (1)

Shridutt Kothari
Shridutt Kothari

Reputation: 7394

The problem you are facing is know problem because, threads are not supposed to be stopped by calling thread.stop(); method.

Also Android discourages the use of Java Threads in Android, and Conveniently, Android has some additional support for when it comes to communicating between Threads, The Handler class provides a neat queued message mechanism, and Looper provides a handy method for processing same.

But as you mentioned you want to show a progress dialog which can be cancelled. When the cancel is pressed, so this type of functionality can be achieved using AsyncTask.

As AsyncTask is one of the easiest ways to implement parallelism in Android without having to deal with more complex methods like Threads. Though it offers a basic level of parallelism with the UI thread, it should not be used for longer operations (of, say, not more than 2 seconds).

Mainly AsyncTask should handle your problem, Since:

  1. It provides easy and standard recommended mechanism to publish background progress (see the Usage section here: http://developer.android.com/reference/android/os/AsyncTask.html)
  2. It provides method cancel(boolean); for cancelling a task(see the Cancelling a task section here: http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask has four methods to do the task:

onPreExecute();
doInBackground();
onProgressUpdate();
onPostExecute();

And cancel(); method to handle the cancellation of the background work.

Where doInBackground() is the most important as it is where background computations are performed.

Code: Here is a skeletal code outline with explanations:

public class AsyncTaskTestActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  

        // This starts the AsyncTask
        // Doesn't need to be in onCreate()
        new DownloadFilesTask().execute(url1);
    }

    // Here is the AsyncTask class:
    //
    // AsyncTask<Params, Progress, Result>.
    //    Params – the type (Object/primitive) you pass to the AsyncTask from .execute() 
    //    Progress – the type that gets passed to onProgressUpdate()
    //    Result – the type returns from doInBackground()
    // Any of them can be String, Integer, Void, etc. 

    private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
 }
}

For more in depth knowledge visit following links:

https://blog.nikitaog.me/2014/10/11/android-looper-handler-handlerthread-i/ http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 1

Related Questions