Android: Toast w wątku

Jak wyświetlić Toast wiadomości z wątku?

Author: Ravindra babu, 2010-06-28

10 answers

Możesz to zrobić, wywołując Activity ' S runOnUiThread metodę z twojego wątku:

activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});
 228
Author: Lauri Lehtinen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-28 17:37:15

Lubię mieć w swojej działalności metodę o nazwie showToast, którą mogę wywołać z dowolnego miejsca...

public void showToast(final String toast)
{
    runOnUiThread(() -> Toast.makeText(MyActivity.this, toast, Toast.LENGTH_SHORT).show());
}

Następnie najczęściej wywołuję go od wewnątrz MyActivity w dowolnym wątku takim jak ten...

showToast(getString(R.string.MyMessage));
 56
Author: mjaggard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-28 10:53:45

Jest to podobne do innych odpowiedzi, jednak zaktualizowane dla nowych dostępnych interfejsów API i znacznie czystsze. Nie zakłada również, że jesteś w kontekście aktywności.

public class MyService extends AnyContextSubclass {

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}
 24
Author: ChrisCM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-30 20:57:35

Jak to lub to , z Runnable, które pokazuje Toast. Mianowicie,

Activity activity = // reference to an Activity
// or
View view = // reference to a View

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        showToast(activity);
    }
});
// or
view.post(new Runnable() {
    @Override
    public void run() {
        showToast(view.getContext());
    }
});

private void showToast(Context ctx) {
    Toast.makeText(ctx, "Hi!", Toast.LENGTH_SHORT).show();
}
 9
Author: yanchenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-15 01:43:47

Jedno podejście, które działa praktycznie wszędzie, w tym z miejsc, w których nie masz Activity lub View, to chwycić Handler do głównego wątku i pokazać toast:

public void toast(final Context context, final String text) {
  Handler handler = new Handler(Looper.getMainLooper());
  handler.post(new Runnable() {
    public void run() {
      Toast.makeText(context, text, Toast.DURATION_LONG).show();
    }
  });
}
Zaletą tego podejścia jest to, że działa z dowolnymi Context, w tym Service i Application.
 7
Author: Mike Laren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-10 17:56:14

Czasami musisz wysłać wiadomość z innego Thread do wątku UI. Ten typ scenariusza występuje, gdy nie można wykonać operacji sieci / IO w wątku interfejsu użytkownika.

Poniższy przykład obsługuje ten scenariusz.

  1. masz wątek UI
  2. musisz uruchomić działanie IO i dlatego nie możesz uruchomić Runnable w wątku UI. Więc wyślij Runnable do Handlera na HandlerThread
  3. Pobierz wynik z Runnable i wyślij go z powrotem do wątku interfejsu i pokaż Toast wiadomość.

Rozwiązanie:

  1. Utwórz HandlerThread i uruchom go
  2. Utwórz Handler Z Looper Z HandlerThread: requestHandler
  3. tworzy obsługę z looperem z głównego wątku: responseHandler i nadpisuje handleMessage metodę
  4. post a Runnable zadanie na requestHandler
  5. Inside Runnable task, call sendMessage on responseHandler
  6. Ten sendMessage wynik wywołania handleMessage W responseHandler.
  7. Get atrybuty from the Message and process it, zaktualizuj interfejs

Przykładowy kod:

    /* Handler thread */

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();
    Handler requestHandler = new Handler(handlerThread.getLooper());

    final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this,
                    "Runnable on HandlerThread is completed and got result:"+(String)msg.obj,
                    Toast.LENGTH_LONG)
                    .show();
        }
    };

    for ( int i=0; i<5; i++) {
        Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                try {

                    /* Add your business logic here and construct the 
                       Messgae which should be handled in UI thread. For 
                       example sake, just sending a simple Text here*/

                    String text = "" + (++rId);
                    Message msg = new Message();

                    msg.obj = text.toString();
                    responseHandler.sendMessage(msg);
                    System.out.println(text.toString());

                } catch (Exception err) {
                    err.printStackTrace();
                }
            }
        };
        requestHandler.post(myRunnable);
    }

Przydatne artykuły:

Handlerthreads-and-why-you-should-be-using-them-in-your-android-apps

Android-looper-handler-handlerthread-i

 6
Author: Ravindra babu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-30 07:13:44
  1. Get UI thread Handler instance and use handler.sendMessage();
  2. wywołanie post() Metoda handler.post();
  3. runOnUiThread()
  4. view.post()
 5
Author: Kerwin You,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-03 13:48:14

Możesz użyć Looper do wysłania Toast wiadomości. Przejdź przez ten link aby uzyskać więcej szczegółów.

public void showToastInThread(final Context context,final String str){
    Looper.prepare();
    MessageQueue queue = Looper.myQueue();
    queue.addIdleHandler(new IdleHandler() {
         int mReqCount = 0;

         @Override
         public boolean queueIdle() {
             if (++mReqCount == 2) {
                  Looper.myLooper().quit();
                  return false;
             } else
                  return true;
         }
    });
    Toast.makeText(context, str,Toast.LENGTH_LONG).show();      
    Looper.loop();
}

I jest wywoływany w Twoim wątku. Kontekst może być Activity.getContext() wychodząc z Activity musisz pokazać toast.

 3
Author: Vinoj John Hosan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-11 08:04:32

Zrobiłem to podejście w oparciu o mjaggard odpowiedź:

public static void toastAnywhere(final String text) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(SuperApplication.getInstance().getApplicationContext(), text, 
                    Toast.LENGTH_LONG).show();
        }
    });
}
Dobrze mi poszło.
 2
Author: Angelo Polotto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-06 18:42:16

Napotkałem ten sam problem:

E/AndroidRuntime: FATAL EXCEPTION: Thread-4
              Process: com.example.languoguang.welcomeapp, PID: 4724
              java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
                  at android.widget.Toast$TN.<init>(Toast.java:393)
                  at android.widget.Toast.<init>(Toast.java:117)
                  at android.widget.Toast.makeText(Toast.java:280)
                  at android.widget.Toast.makeText(Toast.java:270)
                  at com.example.languoguang.welcomeapp.MainActivity$1.run(MainActivity.java:51)
                  at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 4724 SIG: 9
Application terminated.

Before: OnCreate function

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
    }
});
thread.start();

Po: funkcja onCreate

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
    }
});
Zadziałało.
 0
Author: Languoguang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-31 08:58:22