从BroadcastReceiver显示延迟的Toast

时间:2010-09-19 05:00:19

标签: android

我试图在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();
    }
  }
}

当我运行时,我得到以下异常:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

这是做这样事情的正确方法吗?我应该使用其他定时器吗?在这种情况下获取Context对象的正确方法是什么?

谢谢

3 个答案:

答案 0 :(得分:2)

您可以尝试使用my Toaster class。像线程一样使用它:

new Toaster(yourContext, yourMessageResId, Toast.LENGTH_LONG).start();

答案 1 :(得分:1)

在Kevin Gaudin bellow发布的示例的指导下,我意识到为了从不同的线程与UI进行交互,需要手动管理Android消息循环。

在伪中看起来像这样:

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();
    }

}

答案 2 :(得分:0)

这不起作用。一旦你的onReceive()方法完成,手机就可以自由地重新入睡或做任何想做的事情。你必须实现一个唤醒锁。