Android:线程中的吐司
-
01-10-2019 - |
题
我该如何显示 吐司 线程的消息?
解决方案
您可以致电 Activity
' runOnUiThread
线程的方法:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
其他提示
我喜欢在我的活动中使用一种方法 showToast
我可以从任何地方打电话...
public void showToast(final String toast)
{
runOnUiThread(() -> Toast.makeText(MyActivity.this, toast, Toast.LENGTH_SHORT).show());
}
然后,我最常从内部称呼它 MyActivity
在这样的任何线程上...
showToast(getString(R.string.MyMessage));
这类似于其他答案,但是对新的可用API和更清洁的更新。另外,不要假设您处于活动环境中。
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();
}
});
}
}
一种几乎任何地方都可以使用的方法,包括来自您没有的地方 Activity
或者 View
, ,要抓住一个 Handler
到主线程并显示敬酒:
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();
}
});
}
这种方法的优点是它可以与任何 Context
, , 包含 Service
和 Application
.
像 这 或者 这, , Runnable
这显示了 Toast
。即,
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();
}
有时,您必须从另一个 Thread
到UI线程。当您无法在UI线程上执行网络/IO操作时,就会发生这种类型的情况。
下面的示例处理该方案。
- 您有UI线程
- 您必须启动IO操作,因此无法运行
Runnable
在UI线程上。所以张贴你的Runnable
要处理HandlerThread
- 从
Runnable
并将其发送回UI线程并显示Toast
信息。
解决方案:
- 创建一个 处理 并开始
- 创建一个 处理程序 和 looper 从
HandlerThread
:requestHandler
- 从主线程中创建带有Looper的处理程序:
responseHandler
和覆盖handleMessage
方法 post
一种Runnable
任务打开requestHandler
- 里面
Runnable
任务,打电话sendMessage
在responseHandler
- 这
sendMessage
结果调用handleMessage
在responseHandler
. - 从
Message
并处理它,更新UI
示例代码:
/* 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);
}
有用的文章:
- 获取UI线程处理程序实例并使用
handler.sendMessage();
- 称呼
post()
方法handler.post();
runOnUiThread()
view.post()
您可以使用 Looper
发送 Toast
信息。经历这个 关联 更多细节。
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();
}
它在您的线程中被调用。上下文可能是 Activity.getContext()
从 Activity
您必须展示烤面包。
我基于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();
}
});
}
对我来说很好。
我遇到了同样的问题:
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.
之前:ongreate函数
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
thread.start();
之后:ongreate函数
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
有效。
不隶属于 StackOverflow