How can I display Toast messages from a thread?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
I made this approach based on mjaggard answer:
Worked well for me.
You can do it by calling an
Activity
'srunOnUiThread
method from your thread:I like to have a method in my activity called
showToast
which I can call from anywhere...I then most frequently call it from within
MyActivity
on any thread like this...This is similar to other answers, however updated for new available apis and much cleaner. Also, does not assume you're in an Activity Context.
One approach that works from pretty much anywhere, including from places where you don't have an
Activity
orView
, is to grab aHandler
to the main thread and show the toast:The advantage of this approach is that it works with any
Context
, includingService
andApplication
.Sometimes, you have to send message from another
Thread
to UI thread. This type of scenario occurs when you can't execute Network/IO operations on UI thread.Below example handles that scenario.
Runnable
on UI thread. So post yourRunnable
to handler onHandlerThread
Runnable
and send it back to UI thread and show aToast
message.Solution:
HandlerThread
:requestHandler
responseHandler
and overridehandleMessage
methodpost
aRunnable
task onrequestHandler
Runnable
task, callsendMessage
onresponseHandler
sendMessage
result invocation ofhandleMessage
inresponseHandler
.Message
and process it, update UISample code:
Useful articles:
handlerthreads-and-why-you-should-be-using-them-in-your-android-apps
android-looper-handler-handlerthread-i