android alooper,Android - myLooper() vs getMainLooper()

You have it described in the docs:

Returns the application's main looper, which lives in the main thread of the application.

Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.

As for whether getMainLooper() is of any use, I can assure you it really is. If you do some code on a background thread and want to execute code on the UI thread, e.g. update UI, use the following code:

new Handler(Looper.getMainLooper()).post(new Runnable() {

// execute code that must be run on UI thread

});

Of course, there are other ways of achieving that.

Another use is, if you want to check if the currently executed code is running on the UI thread, e.g. you want to throw / assert:

boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();

or

boolean isUiThread = Looper.getMainLooper().isCurrentThread();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值