Handler的使用场合

Handler的使用场合


2024年5月5日发(作者:勒索病毒专杀)

Handler的使用场合:

1、

to schedule messages and runnables to be executed as some point in the future;

安排messages和runnables在将来的某个时间点执行。

2、 to enqueue an action to be performed on a different thread than your own.

将action入队以备在一个不同的线程中执行。即可以实现线程间通信。比如当你创建子线

程时,你可以再你的子线程中拿到父线程中创建的Handler对象,就可以通过该对象向父线程的

消息队列发送消息了。由于Android要求在UI线程中更新界面,因此,可以通过该方法在其它

线程中更新界面。

通过Handler更新UI实例:

步骤:

1、创建Handler对象(此处创建于主线程中便于更新UI)。

2、构建Runnable对象,在Runnable中更新界面。

3、在子线程的run方法中向UI线程post,runnable对象来更新UI。

详细代码如下:

[java] view plaincopyprint?

1. package d;

2.

3. import les;

4. import ty;

5. import ;

6. import r;

7. import ;

8. import kListener;

9. import ;

10. import ew;

11.

12. public class downLoadPractice extends Activity {

13. private Button button_submit=null;

14. private TextView textView=null;

15. private String content=null;

16. private Handler handler=null;

17. /** Called when the activity is first created. */

18. @Override

19. public void onCreate(Bundle savedInstanceState) {

20. te(savedInstanceState);

21. setContentView();

22. //创建属于主线程的handler

23. handler=new Handler();

24.

25. button_submit=(Button)findViewById(_submit);

26. textView=(TextView)findViewById(ew);

27. button_lickListener(new submitOnClieckListener())

;

28. }

29. //为按钮添加监听器

30. class submitOnClieckListener implements OnClickListener{

31. @Override

32. public void onClick(View v) {

33. //本地机器部署为服务器,从本地下载文件内容在textView上显示

34. final DownFiles df=new DownFiles("192.168.75.1:8080

/downLoadServer/");

35. t("正在加载......");

36. new Thread(){

37. public void run(){

38. content=adFiles();

39. (runnableUi);

40. }

41. }.start();

42. }

43.

44. }

45.

46. // 构建Runnable对象,在runnable中更新界面

47. Runnable runnableUi=new Runnable(){

48. @Override

49. public void run() {

50. //更新界面

51. t("the Content is:"+content);

52. }

53.

54. };

55.

56.

57. }

Only the original thread that created a view hierarchy

can touch its views错误

分类: Linux 2011-04-08 12:03 744人阅读 评论(2) 收藏 举报

经常遇到这个错误

Only the original thread that created a view hierarchy can touch its views。

这是因为在工作线程更新了UI,可以使用Handle来处理。

如何区分:

Log.d(TAG, " original thread "+nLooper().getThread().getId());

Log.d(TAG, "currrent thread "+tThread().getId());

如果你对于Android的Thread+Handler方式感觉繁琐,不妨试试Activity提供的另外一种简单

的方法runOnUiThread,runOnUiThread可以帮助你在线程中执行UI更新操作,我们只需要在

线程中写上类似

MyActivity

.iThread(new Runnable() {

@Override

public void run() {

// refresh ui 的操作代码

}

});

这里需要注意的是runOnUiThread是Activity中的方法,在线程中我们需要告诉系统是哪个

activity调用,所以前面显示的指明了activity。


发布者:admin,转转请注明出处:http://www.yc00.com/xitong/1714911336a2536704.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信