从一个BroadcastReceiver显示延迟吐司 [英] Displaying a Delayed Toast from a BroadcastReceiver
问题描述
我试图由一个BroadcastReceiver接收到事件后,以显示信息给用户一定的时间。
I'm trying to display a message to the user some time after an event is received by a BroadcastReceiver.
public class MyReceiver extends BroadcastReceiver {
private Timer timer = new Timer();
@Override
public void onReceive(Context context, Intent intent) {
// Display message in 10 sec.
timer.schedule(new MessageTask(context, "Test Message"), 10 * 1000);
}
private static class MessageTask extends TimerTask {
public MessageTask(Context context, String message) {
this.context = context;
this.message = message;
}
public void run() {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
当我运行此我得到了以下异常:
When I run this I get the following exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
这是做这样的事情的正确方法?我应该用其他的东西那么计时器?什么是拿到一个Context对象,在这种情况下正确的方法是什么?
Is this the right way to do something like this? Should I be using something other then a Timer? And what is the right way to get a Context object in this situation?
感谢您
推荐答案
通过张贴凯文·戈丹波纹管的例子的指导下,我认识到,为了与来自不同的线程的UI交互,需要管理的Android消息循环手动。
Guided by the example posted by Kevin Gaudin bellow, I realize that in order to interact with the UI from a different thread, one needs to manage the Android message loop manually.
在这个伪看起来是这样的:
In pseudo this looks something like this:
import android.content.Context;
import android.os.Looper;
public class MyUIThread extends Thread {
public MyUIThread(Context context) {
// Probably going to need a context to do anything useful. So
// pass it in.
this.context = context;
}
public void run() {
Looper.prepare();
// Do some UI stuff, e.g. Toast.makeText
Looper.loop();
}
}
这篇关于从一个BroadcastReceiver显示延迟吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!