如何显示来自另一个线程中的 Toast 消息 class
How to show Toast messages from a thread in another class
我正在开发一个应用程序,我需要显示来自另一个 class 中运行的线程的 Toast 消息。
我阅读了有关 runOnUiThread 的信息,但它不起作用。在主要活动中,有一个对另一个 java class 的调用,这里有一个到网络服务器的连接,我处理来自服务器的 Http 消息。在这里,如果我收到 204 条消息,我需要祝酒词。如何实现 runOnUiThread?
谢谢
我建议您使用 Retrofit 库。它为您处理所有线程内容,您不必重新发明轮子。
//make request in ui thread
yourService.getMyData().enqueue(new Callback<YourResponse>() {
@Override
public void onResponse(Response<YourResponse> response) {
//handle responses in ui thread
if (response.isSuccess()) {
//Toast.makeText()..
} else {
//error
}
}
@Override
public void onFailure(Throwable t) {
//toast the error
}
});
很漂亮吧?
将您的 activity 的引用传递给该工作人员 class 并像这样调用 runOnUiThread
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Your Message here", Toast.LENGTH_SHORT).show();
}
});
我正在开发一个应用程序,我需要显示来自另一个 class 中运行的线程的 Toast 消息。 我阅读了有关 runOnUiThread 的信息,但它不起作用。在主要活动中,有一个对另一个 java class 的调用,这里有一个到网络服务器的连接,我处理来自服务器的 Http 消息。在这里,如果我收到 204 条消息,我需要祝酒词。如何实现 runOnUiThread?
谢谢
我建议您使用 Retrofit 库。它为您处理所有线程内容,您不必重新发明轮子。
//make request in ui thread
yourService.getMyData().enqueue(new Callback<YourResponse>() {
@Override
public void onResponse(Response<YourResponse> response) {
//handle responses in ui thread
if (response.isSuccess()) {
//Toast.makeText()..
} else {
//error
}
}
@Override
public void onFailure(Throwable t) {
//toast the error
}
});
很漂亮吧?
将您的 activity 的引用传递给该工作人员 class 并像这样调用 runOnUiThread
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Your Message here", Toast.LENGTH_SHORT).show();
}
});