Android:getMainLooper() 和 Looper.myLooper() 之间的区别
我现在正试图复兴一个项目。 getMainLooper() 出现异常...
我认为可能是 MainLooper 初始化有问题,并在此之前添加了 Looper.prepareMainLoop() 。
异常告诉我该对象已经有一个循环器被抛出...
然后我尝试用 Looper.myLooper() 替换 getMainLooper() 并且它起作用了...
但我不明白为什么=)
事实上我不'不明白这两件事之间的区别。我认为在我的项目中使用 getMainLooper() 的地方,它是应用程序的真正主循环程序的最佳位置,但我得到了我得到的..
请解释一下。
感谢您的关注
I'm now trying to resurrect one project.
There was an exception on getMainLooper()...
I thought that may be there's a problem with MainLooper initialization and added Looper.prepareMainLoop() before that.
Exception telling me that there's already a looper for that object was thrown...
Then I tried to replace getMainLooper() with Looper.myLooper() and it worked...
But I didn't understand why=)
In fact I don't get the difference between this two things. I think that on the place where getMainLooper() was used in my project it's the best place for the true main looper of the application but I got what I got..
Please explain.
Thank you for your attention
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不同之处在于
Looper.prepareMainLooper()
在主 UI 线程中准备 Looper。 Android应用程序通常不会调用此函数。由于主线程在第一个活动、服务、提供者或广播接收器启动之前很久就已经准备好了循环程序。但是
Looper.prepare()
在当前线程中准备Looper
。调用该函数后,线程可以调用Looper.loop()
来开始使用Handler
处理消息。因此,在您的情况下,您有两个线程 - X 和 Y。X 线程是主 UI 线程,Android 已准备好其循环程序。当您在 Y 线程中并且调用 Looper.prepareMainLooper() 时,您正在尝试在 X 线程(主线程)中准备循环程序。这失败了,因为 X 的循环器已经准备好了。但是当你在Y线程中调用
Looper.prepare()
时,你实际上是在Y线程中准备looper,因此准备调用Looper.loop()
。The difference is that
Looper.prepareMainLooper()
prepares looper in main UI thread. Android applications normally do not call this function. As main thread has its looper prepared long before first activity, service, provider or broadcast receiver is started.But
Looper.prepare()
preparesLooper
in current thread. After this function is called, thread can callLooper.loop()
to start processing messages withHandler
s.So, in your case you had two threads - X and Y. The X thread is the main UI thread that has its looper already prepared by Android. When you are in Y thread and you're calling
Looper.prepareMainLooper()
you're trying to prepare looper in X thread (main thread). This fails because X's looper is already prepared. But when you callLooper.prepare()
in Y thread, you're actually preparing looper in Y thread and therefore ready to callLooper.loop()
.