【发布时间】:2017-09-29 18:33:48
【问题描述】:
我向用户显示消息通知并在几秒钟后隐藏该通知,我正在使用 postDelayed() 来实现此功能,但问题是当我在隐藏第一条消息之前用新消息更新通知时,我需要重置/重新启动计时器。我找不到任何方法来实现它,因为 removeCallbacks() 只删除待处理的任务。
每当我有新消息要显示在按钮单击时,我都会从MyClass 呼叫showNotification() 并提供新消息。现在,如果我在 4 秒内再次单击该按钮(比如说x 秒)(在隐藏旧通知消息之前)。无法取消旧的 postDelayed 或将计时器重新启动到 4 秒,它会在 4-x 秒后隐藏我的新通知。
MyClass.java
...
// On Button Click - everytime a different message
MyNotification obj = new MyNotification();
obj.showNotification(msg);
...
MyNotification.java
public class MyNotification
{
...
...
private static TextView textview1;
private static MyNotification notification;
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
notification = (MyNotification) this.findViewById(R.id.notification_bar);
textview1 = (TextView) this.findViewById(R.id.textview_notification);
}
Runnable hideNotification = new Runnable() {
@Override
public void run() {
textview1.setVisibility(GONE);
notification.setVisibility(GONE);
}
};
public void showNotification(String msg)
{
textview1.setText(msg);
textview1.setVisibility(VISIBLE);
notification.setVisibility(VISIBLE);
// Hide Toast notification after few secs
notification.postDelayed(hideNotification, 4000);
}
...
}
【问题讨论】:
标签: java android notifications postdelayed