Android: Toast w wątku
Jak wyświetlić Toast wiadomości z wątku?
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();
}
});
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));
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();
}
});
}
}
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();
}
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
.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.
- masz wątek UI
- musisz uruchomić działanie IO i dlatego nie możesz uruchomić
Runnable
w wątku UI. Więc wyślijRunnable
do Handlera naHandlerThread
- Pobierz wynik z
Runnable
i wyślij go z powrotem do wątku interfejsu i pokażToast
wiadomość.
Rozwiązanie:
- Utwórz HandlerThread i uruchom go
- Utwórz Handler Z Looper Z
HandlerThread
:requestHandler
- tworzy obsługę z looperem z głównego wątku:
responseHandler
i nadpisujehandleMessage
metodę -
post
aRunnable
zadanie narequestHandler
- Inside
Runnable
task, callsendMessage
onresponseHandler
- Ten
sendMessage
wynik wywołaniahandleMessage
WresponseHandler
. - 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
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
- Get UI thread Handler instance and use
handler.sendMessage();
- wywołanie
post()
Metodahandler.post();
runOnUiThread()
-
view.post()
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.
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.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.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