Android-Service executes new threads in several ways, androidservice threads

Source: Internet
Author: User

Android-Service executes new threads in several ways, androidservice threads

As we all know, both the service and activity are running in the UI thread, and timeout Data Reading and network time consumption operations must be performed on new threads. The following describes several ways to execute new threads in the service.

1. Traditional java Methods

We all know that the newly created Thread in java can inherit the Thread class or the implement Runnable interface. In essence, it is the run method that implements Runnable. Here, the underlying layer should be the jvm to identify the run method allocation and create a thread. The run method is only used to prepare the resources of the new thread.

The start () native method can start the thread.

1 public interface Runnable {2 3     /**4      * Starts executing the active part of the class' code. This method is5      * called when a thread is started that has been created with a class which6      * implements {@code Runnable}.7      */8     public void run();9 }
1 public class Thread implements Runnable

So the same is true in the service. We can use the Thread class:

 1     @Override 2     public int onStartCommand(Intent intent, int flags, int startId) { 3         L.e(TAG,"onStartCommand"); 4         new Thread(new Runnable() { 5             @Override 6             public void run() { 7  8             } 9         }).start();10         return super.onStartCommand(intent, flags, startId);11     }

You can also implement the Runnable interface:

 1    Runnable runnable= new Runnable() { 2         @Override 3         public void run() { 4             L.e(TAG,  "***********************"); 5         } 6     }; 7     @Override 8     public int onStartCommand(Intent intent, int flags, int startId) { 9         runnable.run();10         return super.onStartCommand(intent, flags, startId);11     }

2. Use IntentService

For details, see the previous blog http://www.cnblogs.com/hxy0107/p/4552486.html

3. Use HandleThread and Headler

Handler itself does not create a new thread, but only the handle for the main UI thread to communicate with the new thread, passing the Message. For details about the next android process communication. The usage is as follows:

 1     final Handler myHandler=new Handler(){ 2  3         @Override 4         public void handleMessage(Message msg) { 5             if(msg.what==0x123){ 6                 L.e(TAG, "handleMessage"); 7             } 8         } 9     };10     @Override11     public void onStart(Intent intent, int startId) {12 13         L.e(TAG,"onStart");14 15    new Thread(new Runnable() {16        @Override17        public void run() {18       myHandler.sendEmptyMessage(0x123);19        }20    }).start();21         super.onStart(intent, startId);22     }

The Handler created in this way is created in the context, so it is bound to the Logoff of the main UI thread, and the message sequence message is also received by the Logoff of the Ui. If we want to bind Handler to a custom thread, we must create a message sequence logoff on the new thread. Fortunately, android has HandlerThread. handlerThread itself is only a Thread, but it implements its own message sequence logoff internally, so that other threads can communicate with our new Thread through handler ~ (Handler must be bound to the Logoff of the new thread)

1 HandlerThread thread = new HandlerThread("MyHandlerThread");2 thread.start();3 mHandler = new Handler(thread.getLooper());4 mHandler.post(new Runnable(){...});
 1   MyHandlerThread myHandlerThread; 2     @Override 3     public void onStart(Intent intent, int startId) { 4  5         L.e(TAG,"onStart"); 6         myHandlerThread=new MyHandlerThread("myhandlerThread"); 7         myHandlerThread.start(); 8         final Handler handlerelse=new Handler(myHandlerThread.getLooper()){ 9 10             @Override11             public void handleMessage(Message msg) {12                 if(msg.what==0x111) {13                     L.e(TAG, "handlerelse handleMessage");14                 }15                 super.handleMessage(msg);16             }17         };18 19         new Thread(new Runnable() {20             @Override21             public void run() {22                 handlerelse.sendEmptyMessage(0x111);23             }24         }).start();25         super.onStart(intent, startId);26     }

The preceding two threads are created. The handlerThread thread has logoff, which allows you to perform operations similar to the interaction between the main UI thread and other threads.

4. TimerTask can be used to send messages at a scheduled time. timerTast is also a method to implement the Runnable interface. A thread is created to send messages at a scheduled time.

1    new Timer().schedule(new TimerTask() {2             @Override3             public void run() {4                 myHandler.sendEmptyMessage(0x123);5             }6         },0,2000);

5. ThreadPool and ThreadPoolExecutor

Writing after dinner...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.