zoukankan      html  css  js  c++  java
  • handler消息机制入门

    handler消息机制入门

     

     为什么要用handle?

    我们在网络上读取图片信息时,是不能把耗时操作放在主线程里面的,当我们在子线程中获取到了图片的消息的时候,我们就需要把这个数据传给主线程。

    而直接使用全局变量是不得行的,因为主线程里面的 tv_txt.setText(str);语句都执行完了后,子线程才给str传值。

    所以我们需要用到handle。

    把子线程获取到的数据放在消息中,然后再handle中处理消息,因为handle被主线程调用,所以这个消息数据最后可以更新主页面。

     1 package com.example.handlerrumen;
     2 
     3 import android.app.Activity;
     4 import android.os.Bundle;
     5 import android.os.Handler;
     6 import android.os.Looper;
     7 import android.os.Message;
     8 import android.util.Log;
     9 import android.widget.TextView;
    10 
    11 public class MainActivity extends Activity {
    12     private TextView tv_txt;
    13     private Handler handler=new Handler(){
    14         //处理消息(被主线程执行)
    15         public void handleMessage(Message msg) {
    16             String str=(String) msg.obj;
    17             tv_txt.setText(str);
    18             
    19             //判断当前函数是否被主线程调用的方式
    20 //            boolean result=Looper.getMainLooper()==Looper.myLooper();
    21 //            Log.d("bh",result+"");
    22         };
    23     };
    24     @Override
    25     protected void onCreate(Bundle savedInstanceState) {
    26         super.onCreate(savedInstanceState);
    27         setContentView(R.layout.activity_main);
    28         tv_txt=(TextView) findViewById(R.id.tv_txt);
    29         //创建子线程,并启动
    30         MyThread myTh=new MyThread();
    31         myTh.start();
    32     }
    33     //自定义子线程
    34     class MyThread extends Thread{
    35         @Override
    36         public void run() {
    37             //伪代码来体现
    38             try {
    39                 Thread.sleep(6000);
    40                 Log.d("bh","访问到网络了");
    41                 String str="我是网络数据";
    42                 //创建message对象
    43                 Message msg=new Message();
    44                 msg.obj=str;
    45                 //发送一个消息
    46                 handler.sendMessage(msg);
    47             } catch (InterruptedException e) {
    48                 e.printStackTrace();
    49             }
    50         }
    51     }
    52 }
  • 相关阅读:
    剑指Offer-合并两个排序的链表
    1. Two Sum&&15. 3Sum&&18. 4Sum
    Sumo生成数据
    357. Count Numbers with Unique Digits
    553. Optimal Division
    147. Insertion Sort List
    24. Swap Nodes in Pairs
    【LeetCode & 剑指offer刷题】发散思维题3:62 圆圈中最后剩下的数字(约瑟夫环问题)
    【LeetCode & 剑指offer刷题】发散思维题2:43 n个骰子的点数
    【LeetCode & 剑指offer刷题】发散思维题1:17 打印从1到最大的n位数
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/7482752.html
Copyright © 2011-2022 走看看