首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Notification 設定播放時長/次數:Notification 無內建屬性,需自行實作定時取消/重發

     編輯:程式設計綜合問答

現狀

`NotificationCompat.Builder` / `Notification` **無 `setDuration`、`setRepeatCount` 等屬性**。系統通知聲音/震動由**用戶系統設定/應用頻道重要性**決定,開發者**無法直接控制具體秒數/次數**。

解決方案:自行封裝定時器控制


public class TimedNotification {
    private NotificationManager manager;
    private int notifyId;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable cancelRunnable;

    public void showTimed(Context ctx, int id, Notification notif, long durationMs) {
        manager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        notifyId = id;
        manager.notify(id, notif);

        // 定時取消
        cancelRunnable = () -> manager.cancel(notifyId);
        handler.postDelayed(cancelRunnable, durationMs);
    }

    public void showRepeating(Context ctx, int id, Notification notif, long intervalMs, int repeatCount) {
        // 類似,配合 postDelayed 遞迴發送/更新
    }

    public void cancel() {
        handler.removeCallbacks(cancelRunnable);
        manager.cancel(notifyId);
    }
}

進階:前台服務 + 自訂聲音播放

  • 啟動 `Foreground Service` (Android 8.0+ 必須),在 `onStartCommand` 中用 `MediaPlayer` 播放自訂鈴聲/語音,**完全可控時長、循環、音量**。
  • 通知只負責顯示 UI,聲音由 Service `MediaPlayer` 掌控。
  • 記得在 `onDestroy` 釋放 `MediaPlayer`、停止前台服務。

避坑

  • **不要嘗試用 `Notification.DEFAULT_SOUND` 配合 `setSound` 控制時長**,系統播放器不受應用控制。
  • **Android 8.0+ 必須建立 `NotificationChannel`**,`importance` 影響預設聲音/震動行為,但無法精確到秒/次。
  • 鎖屏/Doze 模式下 `Handler` 可能延遲,長時間定時請用 `AlarmManager.setExactAndAllowWhileIdle` 或 `WorkManager`。

總結

Notification **無內建播放時長/次數控制**。需求精確控制 → **自行封裝 `Handler`/`AlarmManager` 定時 `cancel`/`notify`**,或**前台服務 + `MediaPlayer` 完全接管音頻播放**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved