开发者

On MultiThreading on the Android platform

开发者 https://www.devze.com 2023-03-25 14:06 出处:网络
Multithreading on Android is to some extent an easy task due to the various possibilities available for us.

Multithreading on Android is to some extent an easy task due to the various possibilities available for us.

However it would be nice to understand the difference between the approaches.

What is the best way to multitask and based on what preferences is it the "best"?

  1. AsyncTask?

    class MultiTasker extends AsyncTask<, , > 
    
  2. Runnable?

    Run开发者_如何学JAVAnable myRun = new Runnable(){
      public void run(){
    
      }
    };
    Thread T = new Thread(myRun);
    T.start();
    
  3. Handler?

    class MultiTasker extends Handler
    


Asking which one is "best" is the wrong approach here - it depends on what you are trying to accomplish.

  1. Runnable/Thread - This is the basic, lowest-level ways to control threading in Java. Provided in the Java APIs, so they're not specific to Android. You can use these in Android programs, but you'll probably want to use one of the other two options for most tasks (or use them in addition to Threads).
  2. Handler - Provided in the Android APIs. You can post() a Runnable directly, or sendMessage() a Message (along with other options, such as providing a delay before processing a Runnable or Message). However, Handler isn't something you would use by itself to provide multithreading - it's use is usually to get back into the main activity (UI) thread. You'd start some other Thread to do a process in the background, and inside of it would post a Runnable using the Handler when you needed to update the UI. Or if you had a task that didn't necessarily need to run in the background, but did need to pop up and do something every so often, you could post a Runnable with a delay to activate later, and then at the end post itself again with a delay.
  3. AsyncTask - Provided in the Android APIs. This class is for doing something on a background thread, optionally providing incremental updates on the UI thread, and ultimately providing an end result on the UI thread. The Params, Progress, and Result generic types are used to provide start parameters, progress update data, and end result data, respectively. Internally, AsyncTask uses Threads, Runnables, and Handlers to accomplish this task.


Its Always better if you go with AsyncTask().. because Thats something which has been built to solve MultiThreading issues in Android..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号