Làm cách nào để hiển thị tin nhắn Toast từ một chuỗi?
Làm cách nào để hiển thị tin nhắn Toast từ một chuỗi?
Câu trả lời:
Bạn có thể làm điều đó bằng cách gọi một Activity's runOnUiThreadphương pháp từ chủ đề của bạn:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
Threadtham chiếu của đối tượng thành Activitytrong Activity's onResume. Bỏ đặt nó trong Activity's onPause. Làm cả hai dưới một synchronizedkhóa mà cả hai Activityvà Threadtôn trọng.
ActivityVí dụ, bạn có thể sử dụng đơn giản helper-class thay vào đó, xem tại đây: stackoverflow.com/a/18280318/1891118
MyActivity.this.runOnUiThread()hoạt động tốt từ bên trong Thread/ AsyncTask.
Tôi muốn có một phương thức trong hoạt động của mình được gọi là phương thức showToastmà tôi có thể gọi từ mọi nơi ...
public void showToast(final String toast)
{
runOnUiThread(() -> Toast.makeText(MyActivity.this, toast, Toast.LENGTH_SHORT).show());
}
Sau đó, tôi thường xuyên gọi nó từ bên trong MyActivitytrên bất kỳ chuỗi nào như thế này ...
showToast(getString(R.string.MyMessage));
Điều này tương tự với các câu trả lời khác, tuy nhiên được cập nhật cho các apis mới có sẵn và sạch hơn nhiều. Ngoài ra, đừng cho rằng bạn đang ở trong Bối cảnh hoạt động.
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();
}
});
}
}
Một cách tiếp cận hoạt động ở hầu hết mọi nơi, kể cả từ những nơi bạn không có Activityhoặc View, là lấy một Handlerchuỗi chính và hiển thị lời chúc mừng:
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.LENGTH_LONG).show();
}
});
}
Ưu điểm của phương pháp này là nó hoạt động với bất kỳ Context, bao gồm Servicevà Application.
Như thế này hoặc thế này , với một Runnablecho thấy Toast. Cụ thể,
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();
}
Đôi khi, bạn phải gửi tin nhắn từ người khác Threadđến chuỗi giao diện người dùng. Loại kịch bản này xảy ra khi bạn không thể thực hiện các hoạt động Mạng / IO trên chuỗi giao diện người dùng.
Ví dụ dưới đây xử lý tình huống đó.
Runnabletrên chuỗi giao diện người dùng. Vì vậy, đăng của bạn Runnableđể xử lý trênHandlerThreadRunnablevà gửi nó trở lại chuỗi giao diện người dùng và hiển thị một Toastthông báo.Giải pháp:
HandlerThread:requestHandlerresponseHandlervà ghi đè handleMessagephương thứcpostmột Runnablenhiệm vụ trênrequestHandlerRunnablecông việc, hãy gọi sendMessagevềresponseHandlersendMessageKết quả này gọi handleMessagetrong responseHandler.Messagevà xử lý nó, cập nhật giao diện người dùngMã mẫu:
/* 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);
}
Các bài viết hữu ích:
handlerthreads-and-why-you-should-be-using-them-in-your-android-apps
handler.sendMessage();post()Phương thức gọihandler.post();runOnUiThread()view.post() Bạn có thể sử dụng Looperđể gửi Toasttin nhắn. Đi qua liên kết này để biết thêm chi tiết.
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();
}
và nó được gọi trong chuỗi của bạn. Bối cảnh có thể Activity.getContext()bắt nguồn từ việc Activitybạn phải nâng cốc chúc mừng.
Tôi thực hiện cách tiếp cận này dựa trên câu trả lời mjaggard:
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();
}
});
}
Làm việc tốt cho tôi.
Tôi gặp phải vấn đề tương tự :
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.
Trước: hàm onCreate
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
thread.start();
Sau: hàm onCreate
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
nó đã làm việc.