设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

Android线程和Handler基础入门

2014-7-11 12:40| 发布者: joejoe0332| 查看: 5732| 评论: 0|原作者: chris|来自: 伯乐在线

摘要: 现在大多数的移动设备已经变得越来越快,但是它们其实也不算是非常快。如果你想让你的APP既可以承受一些繁杂的工作而又不影响用户体验的话,那么必须把任务并行执行。在Android上,我们使用线程。 ...


示例2:使用postDelayed方法

近期本站新介绍的特性中,我每次都要模拟EditText的自动完成功能,每次文字改变后都会触发一个API的调用,从服务器中检索数据。

我想减少APP调用API的次数,所以决定使用Handler的postDelayed方法来实现这个功能。

本例不针对平行处理,只是关于Handler给消息队列发送消息还有安排消息在未来的某一点执行等。

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
// the below code is inside a TextWatcher
// which implements the onTextChanged method
// I've simplified it to only highlight the parts we're
// interested in
 
private long lastChange = 0;
 
@Override
public void onTextChanged(final CharSequence chars,
                          int start, int before, int count) {
 
        // The handler is spawned from the UI thread
        new Handler().postDelayed(
 
            // argument 1 for postDelated = message to be sent
            new Runnable() {
                @Override
                public void run() {
 
                    if (noChangeInText_InTheLastFewSeconds()) {
                        searchAndPopulateListView(chars.toString());  // logic
                    }
                }
            },
 
            // argument 2 for postDelated = delay before execution
            300);
 
        lastChange = System.currentTimeMillis();
}
 
 
private boolean noChangeInText_InTheLastFewSeconds() {
    return System.currentTimeMillis() - lastChange >= 300
}

最后我就把“postAtTime”这个方法作为联系留给读者们了,掌握Handler了吗?如果是的话,那么可以尽情使用线程了。


原文链接: weddingpartyapp   翻译: 伯乐在线 - chris
译文链接: http://blog.jobbole.com/73267/


酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部