“吐司”通过 TimerTask 发送消息
我找到了一些有关如何从子类访问上下文的信息,以及一些有关
runOnUiThread(new Runnable() {
public void run() {
// Do something
}
});
但在我的情况下它不起作用的信息。应用程序仍在运行,但 Activity 可能已被销毁。第一个(主)活动是创建 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);
日志中没有错误/异常。但没有显示烘烤消息。 :-(
现在我不知道我还能做什么/尝试。我希望你们中的某个人可以帮助我。PS
:也许我使用了错误的上下文?但我也尝试了一些其他上下文,例如当前活动的上下文, ApplicationContext
,...。
I found some info about how to access the context from the subclass and also some info about
runOnUiThread(new Runnable() {
public void run() {
// Do something
}
});
But in my case it does not work. The application is still running, but the activity is maybe already destroyed. The first (main) activity is the parent activity of the one where my TimerTask is created. My code:
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);
There is no error/ exception at log. But the toasted message is not shown. :-(
Now I have no Idea what I can else do/ try. I hope someone of you can help me.
P.S.: Maybe I use the wrong context? But I tried also some other context like the Context of the current activity, the ApplicationContext
, ... .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您在这里使用了错误的上下文,即
getParent()
。不要使用getParent()
尝试像这样使用current_Activity.this
,Well you are using the wrong context here that is
getParent()
. Instead of usinggetParent()
try to use thecurrent_Activity.this
like this,与其使用 TimerTask,为什么不使用 AlarmManager 并设置 < a href="http://developer.android.com/reference/android/app/PendingIntent.html" rel="nofollow">PendingIntent 来触发广播?当您发出广播并在您自己制作的 BroadcastReciever 中捕获它时,您将在 BroadcastReciever 中拥有用于显示 Toast 的上下文。这是一个快速的高级示例。
无论您在 Activity 中的何处设置 TimerTask,请执行以下操作:
然后只需在
onRecieve()
方法中创建一个具有yourBroadcastAction
过滤器的 BroadcastReciever像这样做你的吐司:Rather than using a TimerTask, why not user the AlarmManager and set a PendingIntent to fire off a broadcast? When you fire of the broadcast and catch it in your own BroadcastReciever that you've made, you'll have context in your BroadcastReciever with which to display your toast. Here's a quick high level example.
Where ever you're setting up your TimerTask in your activity, do this instead:
Then just create a BroadcastReciever that has a filter for the
yourBroadcastAction
and in theonRecieve()
method do your toast like so: