Android &引用;吐司;通过TimerTask发送的消息

Android &引用;吐司;通过TimerTask发送的消息,android,android-activity,toast,android-context,Android,Android Activity,Toast,Android Context,我找到了一些关于如何从子类访问上下文的信息,还有一些关于 runOnUiThread(new Runnable() { public void run() { // Do something } }); 但在我的情况下,它不起作用。应用程序仍在运行,但活动可能已被销毁。第一个(主)活动是创建我的TimerTask的活动的父活动。我的代码: TimerTask tt = new TimerTask() { @Override public void run() {

我找到了一些关于如何从子类访问上下文的信息,还有一些关于

runOnUiThread(new Runnable() {
  public void run() {
    // Do something
  }
});
但在我的情况下,它不起作用。应用程序仍在运行,但活动可能已被销毁。第一个(主)活动是创建我的TimerTask的活动的父活动。我的代码:

TimerTask tt = new TimerTask() {
  @Override
  public void run() {
    // do something (cut)

    // and at the end show info
    getParent().runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(getParent(),
                  getResources().getString(R.string.st_toast_msg_stopped),
                  Toast.LENGTH_LONG).show();
      }
    });
  }
};
curTimer.schedule(tt, millisecondsUntilStop);
日志中没有错误/异常。但敬酒信息未显示:-(

现在我不知道我还能做什么/尝试什么。我希望你们中有人能帮助我


旁白:也许我使用了错误的上下文?但我也尝试了一些其他上下文,比如当前活动的上下文,
ApplicationContext
,…

,而不是使用TimerTask,为什么不设置用户并设置a来触发广播呢?当您触发广播并在您自己制作的广播接收器中捕获它时,您将我在你的广播接收器中有上下文来显示你的祝酒词。这里有一个快速的高级示例

在活动中设置TimerTask时,请执行以下操作:

AlarmManager alarmManager = (AlarmManager)Context.getSystemService(Context.ALARM_SERVICE);
Intent broadcastIntent = new Intent("yourBroadcastAction");
PendingIntent pendingIntent = PendingIntenet.getBroadcast(this, 0, broadcastIntent, 0);
alarmManager.set(AlarmManager.ELAPSED_REALTIME, millisecondsUntilStop, broadcastIntent);
然后只需创建一个BroadcastReceiver,它为
yourBroadcastAction
创建一个过滤器,并在
onReceive()方法中执行如下操作:

public void onRecieve(Context context, Intent intent){
  Toast.makeText(context,
              getResources().getString(R.string.st_toast_msg_stopped),
              Toast.LENGTH_LONG).show();
}

您在这里使用了错误的上下文,即
getParent()
。请不要使用
getParent()
尝试使用
当前的\u活动。这样

TimerTask tt = new TimerTask() {
  @Override
  public void run() {
    // do something (cut)

    // and at the end show info
    Activity_name.this.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(Activity_name.this,
                  getResources().getString(R.string.st_toast_msg_stopped),
                  Toast.LENGTH_LONG).show();
      }
    });
  }
};

谢谢你的提示。我相信这也会有用的!非常感谢!