服务器之家

服务器之家 > 正文

实例讲解Android多线程应用开发中Handler的使用

时间:2021-05-21 13:50     来源/作者:张钊

其实可以理解Handler为主线程和另外的线程之间进行数据更新的东东,并且Handler在主线程中,并在Handler直接调用线程的run方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.Handler02;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
 
public class Handler02Activity extends Activity {
  /** Called when the activity is first created. */
  private Handler handler=new Handler();
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handler.post(thread1);
    setContentView(R.layout.main);
    
    System.out.println("================Main==============="+Thread.currentThread().getId());
    System.out.println("============Main========="+Thread.currentThread().getName());
  }
  Runnable thread1=new Runnable() {
     
    @Override
    public void run() {
      System.out.println("======thread1==============="+Thread.currentThread().getId());
      System.out.println("========thread1============"+Thread.currentThread().getName());
      try {
        Thread.sleep(10000);
      } catch (Exception e) {
        // TODO: handle exception
      }
       
    }
  };
}

结果是主线程等待10s后才显示出来,并且线程ID

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.Handler4;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
 
public class Handler4Activity extends Activity {
  /** Called when the activity is first created. */
  private TextView textView;
  private MyHandler myHandler=new MyHandler();
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView=(TextView)this.findViewById(R.id.textView1);
  }
  class MyHandler extends Handler{
    //从消息队列中取出并handleMessage处理消息
    @Override
    public void handleMessage(Message msg) {
      textView.setText((String)msg.obj);
    }
  }
  public void download(View view){
    Thread thread=new Thread(new Runnable() {
       
      @Override
      public void run() {
        try {
          String s="zhangzhao";
          Thread.sleep(5000);
          //数据发送出来
          //textView.setText(s);
          Message message=Message.obtain();//最好不要new,这个obtain会节省资源
          message.obj=s;
          myHandler.sendMessage(message);//没有指定looper那么就会发送给主线程中的looper
           
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
         
      }
       
    });
    thread.start();//会出错原因是在非UI线程里面直接操作UI
    //主线程维护了一个消息对列,当其他的线程有数据需要传递给主线程的时候,你就把数据封装成一个Message对象,然后放在主线程的
    //消息队列中去,对应消息的处理由Looper,子线程通过Handler把下载完的数据封装到Message里面,然后把消息取出来交给Handler进行处理
    //通过Handle和Message实现两个线程之间达到共享数据
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.Handler5;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
 
public class Handler5Activity extends Activity {
  /** Called when the activity is first created. */
  private ProgressBar progressBar;
  private Button button;
  private TextView textView;
  private MyHandler myHandler=new MyHandler();
  int i=0;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   
    setContentView(R.layout.main);
    progressBar = (ProgressBar)this.findViewById(R.id.progressBar1);
    textView=(TextView)this.findViewById(R.id.textView1);
  }
  class MyHandler extends Handler{
    @Override
    public void handleMessage(Message msg) {
      int pos =(Integer)msg.obj;
      progressBar.setProgress(pos);
      textView.setText(pos+"%");
       
    }
  }
  public void downLoad(View view){
      
    new Thread(new Runnable() {
       
      @Override
      public void run() {
        while(i<=100){
          try {
            Thread.sleep(300);
            i+=10;
            Message message=Message.obtain();
            message.obj=i;
            myHandler.sendMessage(message);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
         
        }
         
      }
    }).start();
  }
}

效果:

实例讲解Android多线程应用开发中Handler的使用

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部