总结Android中多线程更新应用的页面信息的方式

时间:2022-11-19 10:41:47

一、runonuithread的用法
runonuithread是activity的内部方法,使用时最好指定当前的环境变量(context)。

?
1
2
3
4
5
6
7
8
9
10
11
12
new thread(new runnable() {
 
    @override
    public void run() {
      runonuithread(new runnable() {
        public void run() {
          toast.maketext(mainactivity.this,"ui操作。。。",0).show();
        }
      });
 
    }
  }).start();

执行runonuithread这个方法会调用父类中的

?
1
2
3
4
5
6
7
public final void runonuithread(runnable action){
 if(thread.currentthread()!=muithread){
 mhandler.post(action);
 }else{
  action.run();
 }
}

二、新线程中view直接在ui线程中更新的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
textview.postdelayed(new runnable() {
 
    @override
    public void run() {
      textview.settext("test view.post(runnable)");
 
    }
  }, 1000);
-
 
 textview.post(new runnable() {
 
    @override
    public void run() {
      textview.settext("test view.postdelay(runnable,long)");
 
    }
  });

三、handler(消息传递机制)使用

?
1
2
3
4
5
handler myhandler = new handler(){
 public void handlemessage(message msg){
  super.handlemessage(msg);
  }
};

也可以继承handler

?
1
2
3
4
5
6
7
8
9
class myhandler extends handler{
  public myhandler(){
 
 }
 @override
 public void handlemessage(message msg){
  super.handlemessage(msg);
 }
}

分发message或者runnable对象到handler所在的线程中一般handler在主线程中。

handler中一些分发消息的方法:

  • post(runnable)
  • postattime(runnable,long)
  • postdelay(runnable,long)
  • sendemptymessage(int what)
  • sendmessage(message)
  • senmessageattime(message,long)
  • sendmessagedelayed(message,long)

post方式添加一个实现runnable接口的匿名对象到消息对列中,在目标收到消息后就可以以回调的方式在自己的线程中执行

message对象所具有的属性:

属性 类型 描述
arg1 int 用来存放整型数据
arg2 int 用来存放整型数据
obj object 用来存放发送给接收器的object任意对象
replyto messager 用来指定此message发送到何处的可选message对象
what int 用于指定用户自定义的消息代码这样接受者就可以了解这个消息的信息

 

?
1
2
3
4
5
6
7
8
message message = message.obtain();
message.arg1 = 1;
message.arg2 = 2;
message.obj = "demo";
message.what = 3;
bundle bundle = new bundle();
bundle.putstring( "name","lucy");
message.setdata(bundle);

下面贴上一段示例代码(开启新线程实现电子广告牌)

?
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
public class mainactivity extends activity implements runnable {
 
  private imageview iv;
  private textview tv;
 
  private handler handler;
  private int[] path = new int[]{r.drawable.img01,r.drawable.img02,r.drawable.img03,r.drawable.img04,
      r.drawable.img05,r.drawable.img06};
  private string[] java" id="highlighter_179200">
?
1
private class mytask extends asynctask<params, progress, result> { ... }

示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private class downloadfilestask extends asynctask<url, integer, long> {
 protected long doinbackground(url... urls) {
   int count = urls.length;
   long totalsize = 0;
   for (int i = 0; i < count; i++) {
     totalsize += downloader.downloadfile(urls[i]);
     publishprogress((int) ((i / (float) count) * 100));
     // escape early if cancel() is called
     if (iscancelled()) break;
   }
   return totalsize;
 }
 
 protected void onprogressupdate(integer... progress) {
   setprogresspercent(progress[0]);
 }
 
 protected void onpostexecute(long result) {
   showdialog("downloaded " + result + " bytes");
 }
}

获取网络图片的示例代码:

?
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
60
public class mainactivity extends actionbaractivity {
 private imageview iv;
 private button bt;
 private string imagepath = "http://192.168.1.1/sa";
 private progressdialog dialog;
 
 @override
 protected void oncreate(bundle savedinstancestate) {
   super.oncreate(savedinstancestate);
   setcontentview(r.layout.activity_main);
   iv = (imageview) findviewbyid(r.id.imageview1);
   bt = (button) findviewbyid(r.id.button1);
   dialog = new progressdialog(this);
   dialog.settitle("提示信息:");
   dialog.setmessage("正在下载。。。");
   bt.setonclicklistener(new onclicklistener() {
 
     @override
     public void onclick(view v) {
       new mytask().execute(imagepath);
 
     }
   });
 }
 public class mytask extends asynctask<string, void, bitmap>{
 
   @override
   protected bitmap doinbackground(string... params) {
     httpclient httpclient = new defaulthttpclient();
     httpget httpget = new httpget(params[0]);
     bitmap bitmap = null;
     try {
       httpresponse httpresponse = httpclient.execute(httpget);
       if (httpresponse.getstatusline().getstatuscode()==200) {
         httpentity httpentity = httpresponse.getentity();
         byte[] data = entityutils.tobytearray(httpentity);
         bitmap= bitmapfactory.decodebytearray(data, 0, data.length);
       }
     } catch (exception e) {
 
       e.printstacktrace();
     }
 
     return bitmap;
   }
 
   @override
   protected void onpreexecute() {     
     super.onpreexecute();
     dialog.show();
   }
 
   @override
   protected void onpostexecute(bitmap result) {     
     super.onpostexecute(result);
     iv.setimagebitmap(result);
     dialog.dismiss();
   }   
  
 }

延伸 · 阅读

精彩推荐