2013-03-26 58 views
4

是否可以在一段時間後自動消失?5分鐘後通知消失

+0

[幾秒後清除通知]的可能的複製(https://stackoverflow.com/questions/4994126/clearing-notification-after-a-few-seconds) – mike47 2017-07-22 18:41:28

回答

1

是的,您可以創建一個在後臺運行並在五分鐘後超時並刪除通知的服務。你是否「應該」實際做到這一點就有待辯論。通知應該在那裏通知用戶...並且用戶應該能夠自行解僱。

From d.android.com:

A服務是可以執行長時間運行在後臺 操作,並且不提供用戶界面的應用程序組件。

4

您可以使用AlarmManager。我認爲比Android服務更合適,更容易實現。

隨着AlarmManager你不需要擔心做些事情,直到完成時間。 Android會爲你做這件事,並且當它發生時發送brodcast。您的申請必須有一個接收器才能獲得正確的意圖。

看論文的例子:

0

你也可以使用一個經典的Java可運行一個簡單的小線頭。

Handler h = new Handler(); 
    long delayInMilliseconds = 5000; 
    h.postDelayed(new Runnable() { 
     public void run() { 
      mNotificationManager.cancel(id); 
     } 
    }, delayInMilliseconds); 

也看這裏:

Clearing notification after a few seconds

0

是的,這是很容易的。 如果您收到通知,那麼如果用戶未讀取通知,請添加一個處理程序,然後刪除通知。

@Override 
public void onMessageReceived(RemoteMessage message) { 
sendNotification(message.getData().toString); 
} 

新增通知代碼

private void sendNotification(String messageBody) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setContentTitle("TEST NOTIFICATION") 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     int id = 0; 
     notificationManager.notify(id, notificationBuilder.build()); 
     removeNotification(id); 
    } 

取消通知代碼。

private void removeNotification(int id) { 
Handler handler = new Handler(); 
    long delayInMilliseconds = 20000; 
    handler.postDelayed(new Runnable() { 
     public void run() { 
      notificationManager.cancel(id); 
     } 
    }, delayInMilliseconds); 
} 
+0

不適用於Android至少4.4和5.0 – Stony 2017-12-20 07:45:58