Android displays toast in a non-UI thread

Source: Internet
Author: User

[Java]View Plaincopyprint?
    1. Public void showtoast (String msg) {
    2. Looper.prepare ();
    3. Toast.maketext (Getapplicationcontext (), MSG, Toast.length_short). Show ();
    4. Looper.loop ();
    5. }
public void Showtoast (String msg) {looper.prepare (); Toast.maketext (Getapplicationcontext (), MSG, Toast.length_short). Show (); Looper.loop ();}

Just add those two sentences to show toast in a non-UI thread

[Java]View Plaincopyprint?
    1. The show () inside the toast
    2. public void Show () {
    3. ...
    4. Service.enqueuetoast (pkg, TN, mduration); //Put this toast into a queue
    5. ...
    6. }
Inside the toast Show () public    Void Show () {      ...        Service.enqueuetoast (Pkg, TN, mduration);   Insert this toast into a queue ...    }

[Java]View Plaincopyprint?
  1. Looper
  2. Public static final void prepare () {
  3. if (sthreadlocal.get () = null) {
  4. throw new runtimeexception ("Only one Looper could be  Created per thread ");
  5. }
  6. Sthreadlocal.set (new Looper ()); //Create a looper in the current thread
  7. }
  8. Private Looper () {
  9. Mqueue = New  MessageQueue ();  //Key here, create what looper have done. is actually creating a message queue
  10. Mrun = true  ;
  11. Mthread = Thread.CurrentThread ();
  12. }
Looperpublic static final void prepare () {        if (sthreadlocal.get () = null) {            throw new RuntimeException ("only one Looper may created per thread ");       Sthreadlocal.set (New Looper ());  Creates a Looper    }private Looper () {        mqueue = new MessageQueue () in the current thread;  The key here is to create what looper have done. In fact, the message queue is created        Mrun = true;        Mthread = Thread.CurrentThread ();    }



Summary: The prerequisites for Toast display:
1:toast display needs to appear in a thread's message queue .... Very discreet.

Reproduced in: http://blog.csdn.net/xiaanming/article/details/8904645

Android displays toast in a non-UI thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.