欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-02-23 12:55:22
一、runonuithread的用法 runonuithread是activity的内部方法,使用时最好指定当前的环境变量(context)。 new thre...

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

new thread(new runnable() {

    @override
    public void run() {
      runonuithread(new runnable() {
        public void run() {
          toast.maketext(mainactivity.this,"ui操作。。。",0).show();
        }
      });

    }
  }).start();

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

public final void runonuithread(runnable action){
 if(thread.currentthread()!=muithread){
 mhandler.post(action);
 }else{
  action.run();
 }
}

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

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(消息传递机制)使用

handler myhandler = new handler(){
 public void handlemessage(message msg){
  super.handlemessage(msg); 
  }
};

也可以继承handler

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 用于指定用户自定义的消息代码这样接受者就可以了解这个消息的信息

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);

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

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[] title = new string[]{"编程词典系列","高效开发","快乐分享","用户人群","快速学习","全方位查询"};
  private int index =0;
  @override
  protected void oncreate(bundle savedinstancestate) {

    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    iv = (imageview) findviewbyid(r.id.imageview1);
    tv = (textview) findviewbyid(r.id.textview1);


    thread t = new thread(this);
    t.start();
    handler = new handler(){
      public void handlemessage(message msg){
        if (msg.what ==1) {
          tv.settext(msg.getdata().getstring("title"));
          iv.setimageresource(path[msg.arg1]);
        }
        super.handlemessage(msg);
      }
    };


  }

  @override
  public void run() {

    while(!thread.currentthread().isinterrupted()){
      index = new random().nextint(path.length);
      message m = handler.obtainmessage();
      m.arg1 = index;
      bundle bundle = new bundle();
      m.what = 1;
      bundle.putstring("title", title[index]);
      m.setdata(bundle);
      handler.sendmessage(m);
      try {
        thread.sleep(2000);
      } catch (interruptedexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      }      
    }    

  }

  }

四、asynctask异步任务的用法

  • asynctask实际上是一个线程池,在代码上比handler要轻量级但是实际上要比handler要耗资源,handler仅仅发送了一个消息队列,连线程池对没有开。
  • onpreexecute(),(可选方法)最新用户调用excute时的接口,任务执行之前调用该方法,可以在这里显示进度对话框。
  • doinbackground(params...),后台执行比较好使的操作,不能直接操纵ui。在该方法中使用publishprogress(progress...)来更新任务的进度。
  • onprogressupdate(progress...),在主线程中执行,显示进度条
  • onpostexecute(result),此方法可以从doinbackground得到的结果来操作ui,在主线程中执行,执行的结果作为参数返回。
  • oncancelled(object)调用此方法可以随时取消操作。

asynctask定义的三种泛型

  • params: 启动任务执行的输入参数,如:http请求的url
  • progress:后台任务执行的百分比
  • result:返回结果,如:string、list集合等
 private class mytask extends asynctask<params, progress, result> { ... }

示例代码:

  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");
   }
  }

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

 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();
    }    
   }  
  }