Android:getMainLooper() 和 Looper.myLooper() 之间的区别

发布于 2024-11-25 21:04:38 字数 347 浏览 3 评论 0原文

我现在正试图复兴一个项目。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魔法少女 2024-12-02 21:04:38

不同之处在于 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() prepares Looper in current thread. After this function is called, thread can call Looper.loop() to start processing messages with Handlers.

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 call Looper.prepare() in Y thread, you're actually preparing looper in Y thread and therefore ready to call Looper.loop().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文