handler详解

时间 : 15-11-09 栏目 : Android, 移动开发 作者 : noway 评论 : 0 点击 : 337 次

  1. handler详解

    文章分类:移动开发

    android里面对于异步消息的处理,提供了一套Handler的实现方案。Handler有很多适宜的应用和微妙之处,使它在和Thread以及Service等一起使用的时候达到很好的效果。

    一. Handler与Thread的区别。Handler与调用者处于同一线程,如果Handler里面做耗时的动作,调用者线程会阻塞。Android UI操作不是线程安全的,并且这些操作必须在UI线程中执行。Android提供了几种基本的可以在其他线程中处理UI操作的方案,包括Activity 的runOnUiThread(Runnable),View的post以及1.5版本的工具类AsyncTask等方案都采用了 Handler,Handler的post对线程的处理也不是真正start一个新的线程,而是直接调用了线程的run方法,这正是google煞费苦心搞一套Handler的用意。

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startThread();
    // sendMessage();
    SystemClock.sleep(2000);
    setContentView(R.layout.main);
    }

    public void startThread() {

    mThread.start();
    }

    public void sendMessage() {
    MHandler mHandler = new MHandler();
    Message msg = mHandler.obtainMessage();
    msg.sendToTarget();
    }

    class MHandler extends Handler {
    public MHandler() {
    }

    public MHandler(Looper l) {
    super(l);
    }

    @Override
    public void handleMessage(Message msg) {
    int count = 0;
    while (count++ < Integer.MAX_VALUE) {
    Log.d(TAG, "Rintail");
    }
    }
    }

    Thread mThread = new Thread() {
    @Override
    public void run() {
    int count = 0;
    while (count++ < Integer.MAX_VALUE) {
    Log.d(TAG, "Rintail");
    }
    }
    };

    二.    Handler对于Message的处理不是并发的。一个Looper 只有处理完一条Message才会读取下一条,所以消息的处理是阻塞形式的。但是如果用不同的Looper则能达到并发的目的。Service 中,onStart的执行也是阻塞的。如果一个startService在onStart执行完成之前,再次条用startService也会阻塞。如果希望能尽快的执行onStart则可以在onStart中使用handler,因为Message的send是非阻塞的。如果要是不同消息的处理也是并发的,则可以用不同的Looper实例化Handler。

    public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    sendMessageWithLooper();
    //sendMessage();
    }
    public void sendMessage() {
    MHandler mHandler = new MHandler();
    Message msg = mHandler.obtainMessage();
    msg.sendToTarget();
    }

    public void sendMessageWithLooper() {
    HandlerThread ht = new HandlerThread("Rintail");
    ht.start();
    MHandler mHandler = new MHandler(ht.getLooper());
    Message msg = mHandler.obtainMessage();
    msg.sendToTarget();
    }

    class MHandler extends Handler {
    public MHandler() {
    }

    public MHandler(Looper l) {
    super(l);
    }

    @Override
    public void handleMessage(Message msg) {
    Log.d(TAG, "first");
    while (true) {
    if (false)
    break;
    }
    Log.d(TAG, "second");
    }
    };

    class MyThread extends Thread {
    @Override
    public void run() {
    Log.d(TAG, "first");
    while (true) {
    if (false)
    break;
    }
    Log.d(TAG, "second");
    }
    };

    三。  资源回收

    向Handler对象发送类似new Message ()形式的空Message可以达到清空Message的目的,这种做法与getLooper().quit()的做法是一样的。如果利用的资源较多,应及时清理。

     

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog-old.z3a105.com/?p=782

handler详解:等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群


0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!

KUBET