android子线程handler获取数据

来源:互联网 发布:绝地求生什么时候优化 编辑:程序博客网 时间:2024/06/02 04:17

今天和大家分享下android 获取接口时,开通子线程进行异步获取数据。

我这边选用的是handler机制。在handler有多种获取方法。今天介绍的是一种比较流行,效率较高的一种方法:obtainMessage()。这种用的相对较少,毕竟常见的是sendMessage()。我们先来对比下,首先看sendMessage的写法



private Handler handler = new Handler() {
@SuppressLint("ShowToast")
@Override
public void handleMessage(Message msg) {
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case 0:
 
case 1:
 
break;
case 2:
 
break;
case -1:
 
break;
}
}
super.handleMessage(msg);
}
};

private void sendMsg(int flag) {
Message msg = new Message();
msg.what = flag;
handler.sendMessage(msg);
}

使用的话直接就是 sendMsg(1);

源码为:

  1. /** 
  2.     * Returns a new {@link android.os.Message Message} from the global message pool.  
  3.   * More efficient than creating and allocating new instances.  
  4.    * The retrieved message has its handler set to this instance     
  5.   * (Message.target == this). 
  6.     * If you don't want that facility, just call Message.obtain() instead. 
  7.     */  
  8.     
  9.   
  10.    public final Message obtainMessage()  
  11.    {  
  12.        return Message.obtain(this);  
  13.    }  

而obtainMessage()的使用是:

private Handler mHandler = new Handler(new Handler.Callback() {    @Override    public boolean handleMessage(Message msg) {        if (“当前activity”!= null && !"当前activity".isFinishing()) {            Result result = (Result) msg.obj;            if (result != null) {                List<Qiang> qiangs = result.getData();                if (qiangs != null) {                    mAdapter.setQiangs(qiangs);                }            }        }        return false;    }});
mHandler.obtainMessage(0, result).sendToTarget();//result是object类型的,可以看下源码
public final Message obtainMessage(int what, Object obj){    return Message.obtain(this, what, obj);}
我们在看看sendToTargt()的源码:
/** * Pushes a message onto the end of the message queue after all pending messages * before the current time. It will be received in {@link #handleMessage}, * in the thread attached to this handler. *   * @return Returns true if the message was successfully placed in to the  *         message queue.  Returns false on failure, usually because the *         looper processing the message queue is exiting. */public final boolean sendMessage(Message msg){    return sendMessagmeDelayed(msg, 0);}
备注中写的比较详细了,这个msg不是new出来的,而是message queue中的,省去了对象申请的内存,
建议大家还是按照obtainMessage()的写法来写:)

0 0
原创粉丝点击