简体   繁体   English

处理程序与线程

[英]Handler vs Thread

I would like to know, once for all. 我想知道,一劳永逸。 I've read in many places. 我在很多地方读过。 When I want do some 'long time operations' I should use a Handler . 当我想做一些“长时间操作”时,我应该使用Handler

But I don't get why? 但我不明白为什么? All my 'long-time-operations' I surround with a regular threads, and it works fine. 所有我的'长时间操作'我用常规线程包围,它工作正常。

Why would I use Handler for this? 为什么我会使用Handler呢?

The only time I had to use Handler was, when I had to schedule some task( postDelayed ) 我不得不使用Handler的唯一一次,当我不得不安排一些任务时( postDelayed

Is there any main idea I miss about handlers (When I should really use it)? 我是否有任何关于handlers主要想法(当我真的应该使用它时)? Or maybe there isn't really difference? 或者也许没有真正的区别?

A Handler lets you communicate back with the UI thread from your background thread. Handler允许您与后台线程中的UI线程进行通信。 This is because UI operations are forbidden from within background threads. 这是因为在后台线程中禁止UI操作。 Note that starting at version 1.5, the AsyncTask class makes it much easier to do so. 请注意,从1.5版开始, AsyncTask类使得更容易实现。

It can't just be about getting you back to the UI thread since runOnUiThread(Runnable) does that very nicely. 它不仅仅是让你回到UI线程,因为runOnUiThread(Runnable)做得非常好。 I suspect this is more about making it easier for Android to manage threads and other resources that shouldn't live outside of an Activity's context, and that the "Activity has leaked..." exceptions tell you when that's happened. 我怀疑这更多的是让Android更容易管理线程和其他资源,这些资源不应该存在于Activity的上下文之外,并且“Activity已经泄露......”异常会告诉您何时发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM