android子线程handler获取数据

今天和大家分享下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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值