1

我想在自定义的时间内显示一条消息或通知,在这种情况下不到 2 秒。

我尝试了两种方法,但都没有真正的帮助: 1. 通过 Toast 显示消息并通过设置持续时间LENGTH_SHORT,这显然定义了 2 秒的硬编码持续时间。-> 失败 2. 创建一个NotificationCompat.Builder例程SetTicker并在一定时间后取消通知。-> 通知(我并不真正需要)在给定时间后消失,但不幸的是,自动收报机会停留更长的时间。:(

private void SetNotification(CharSequence aCharSeq)
{
  Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
  PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
    m_RandNotificationID, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

  NotificationCompat.Builder builder = new    NotificationCompat.Builder(this).setTicker(aCharSeq)
    .setContentTitle(aCharSeq).setContentText(aCharSeq).setSmallIcon(R.drawable.sound)
    .setContentIntent(contentIntent);

  Notification noti = builder.build();

  m_NotMan.notify(m_RandNotificationID, noti);

  new Timer().schedule(CancelAction, 1000L);
}

TimerTask CancelAction = new TimerTask()
{
   public void run()
   {
     m_NotMan.cancel(m_RandNotificationID);
   }
};

您的任何想法都会有所帮助。:)

新年快乐

克里斯

4

1 回答 1

3

正如您已经提到的, a 的持续时间Toast只能设置为Toast.LENGTH_SHORTand Toast.LENGTH_LONG。但是,可以Toast通过提前取消它来显示短于 2 秒的时间,例如在 1 秒后,使用Handler.

final Toast toast = Toast.makeText(this, "Example Toast",
        Toast.LENGTH_SHORT);
toast.show();

new Handler().postDelayed(new Runnable() {

    @Override
    public void run() {
        toast.cancel();
    }
}, 1000);
于 2013-01-01T14:14:40.983 回答