Jimmy
Jimmy

Reputation: 13

How to use setOnTouchListener and Threads?

Currently, I have a setOnTouchListener in the onCreate section of my app. But the setOnTouchListener is doing some heavy calculation and stuff which is causing my app to not respond and close.

something.setOnTouchListener(new ImageView.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            /* Heavy stuff*/
        }
    });

I saw a tutorial on Youtube and the guy said that, whenever there is some kind of heavy calculation or something, one mustn't put that in onCreate or else the app will display the "Not Responding message", and to solve that problem one must use Threads.

So can anybody please tell me how to use threads for the inside of the setOnTouchListener.

Upvotes: 1

Views: 301

Answers (1)

TejjD
TejjD

Reputation: 2571

What you are looking for is an Async Task.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Traditionally, you are basically executing a task asynchronously, so that it does not hang the UI. This is what results in what you experience: "which is causing my app to not respond and close."


As taken from Vogella:


  1. AsyncTask

7.1. Purpose of the AsyncTask class

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

7.2. Using the AsyncTask class

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask .

An AsyncTask is started via the execute() method.

The execute() method calls the doInBackground() and the onPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.

The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.

The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

7.3. Parallel execution of several AsyncTasks

Android executes AsyncTask tasks before Android 1.6 and again as of Android 3.0 in sequence by default.

You can tell Android to run it in parallel with the usage of the executeOnExecutor() method, specifying AsyncTask.THREAD_POOL_EXECUTOR as first parameter.

The following code snippet demonstrates that.

// ImageLoader extends AsyncTask
ImageLoader imageLoader = new ImageLoader(imageView);

// Execute in parallel
imageLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png"); 

7.4. Disadvantages of using AsyncTasks

The AsyncTask does not handle configuration changes automatically, i.e. if the activity is recreated, the programmer has to handle that in his coding.

A common solution to this is to declare the AsyncTask in a retained headless fragment.

Check this out for a good overview and example of how you can achieve it: Handlers, Async Tasks and Threads - Vogella.

Upvotes: 1

Related Questions