1. 程式人生 > >Android 中Notification進度條一直彈出提示及提示音

Android 中Notification進度條一直彈出提示及提示音

Android 8.0中Notification的Progress每次更新進度,都會彈出提示,並且有提示音。原始碼如下

public void notifyDownloading(long progress, long num, String file_name) {
    Notification.Builder mBuilder;
mBuilder = new Notification.Builder(MainActivity.this, TAG);
NotificationChannel channel;
channel = new NotificationChannel(TAG , file_name, 
NotificationManager.IMPORTANCE_MAX);
mNotifyManager.createNotificationChannel(channel); mBuilder.setSmallIcon(R.drawable.notification_download_icon); mBuilder.setProgress((int) num, (int) progress, false); mBuilder.setContentInfo(getPercent((int) progress, (int) num)); mBuilder.setOngoing(true); mBuilder.setWhen(System.currentTimeMillis
()); mBuilder.setContentTitle(file_name); mBuilder.setContentText("download"); PendingIntent pendIntent = PendingIntent.getActivity( MainActivity.this, NOTIFY_ID, getCurActivityIntent(), PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendIntent); mNotifyManager.notify(NOTIFY_ID
, mBuilder.build()); }

這裡需要修改NotificationChannel的importance屬性:

/**
 * Min notification importance: only shows in the shade, below the fold.
 */
public static final int IMPORTANCE_MIN = 1;
/**
 * Low notification importance: shows everywhere, but is not intrusive.
 */
public static final int IMPORTANCE_LOW = 2;
/**
 * Default notification importance: shows everywhere, makes noise, but does not visually
 * intrude.
 */
public static final int IMPORTANCE_DEFAULT = 3;
/**
 * Higher notification importance: shows everywhere, makes noise and peeks. May use full screen
 * intents.
 */
public static final int IMPORTANCE_HIGH = 4;
/**
 * Unused.
 */
public static final int IMPORTANCE_MAX = 5;

這裡的IMPORTANCE_MAX應該和IMPORTANCE_HIGH屬性類似,表示顯示時有聲音,且會出現彈框提示。在Android 8.0中,這樣設定後,Progress每次更新都會有聲音和彈框。

把IMPORTANCE_MAX修改為IMPORTANCE_LOW,則不會出現該現象。

修改後程式碼如下:

public void notifyDownloading(long progress, long num, String file_name) {
    Notification.Builder mBuilder;
mBuilder = new Notification.Builder(MainActivity.this, TAG );
NotificationChannel channel;
channel = new NotificationChannel(TAG, file_name, NotificationManager.IMPORTANCE_LOW);
mNotifyManager.createNotificationChannel(channel);
mBuilder.setSmallIcon(R.drawable.notification_download_icon);
mBuilder.setProgress((int) num, (int) progress, false);
mBuilder.setContentInfo(getPercent((int) progress, (int) num));
mBuilder.setOngoing(true);
mBuilder.setWhen(System.currentTimeMillis());
mBuilder.setContentTitle(file_name);
mBuilder.setContentText("download");
PendingIntent pendIntent = PendingIntent.getActivity(
            MainActivity.this, NOTIFY_ID, getCurActivityIntent(), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendIntent);
mNotifyManager.notify(NOTIFY_ID, mBuilder.build());
}