前台Service通知栏进度更新, 解决Android O (8.0) Notification不显示问题

1.通知栏常驻, 确保Service为前台进程, 防止服务被杀死

2.使用标准的通知栏样式

notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    LogUtil.d(TAG, "onStartCommand");
    final Integer notificationID = 100;
    //Set notification information:
    final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL);
    notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_round)
            .setContentTitle("小米视频")
            .setContentText("甄嬛传,老男孩等下载中")
            .setProgress(100, 0, false);
    //Send the notification:
    final Notification notification = notificationBuilder.build();
    startForeground(notificationID, notification);
    UIThread.uiPost(new Runnable() {
        @Override
        public void run() {
            if (progress == 100) {
                stopForeground(true);
                return;
            }
            notificationBuilder.setProgress(100, progress++, false);
            Notification notification = notificationBuilder.build();
            notificationManager.notify(notificationID, notification);
            UIThread.uiPost(this,100);
        }
    }, 100);
    return START_STICKY;
}

解决Android O (8.0)通知栏不显示问题, 需要为NotificationManager设置NotificationChannel

/**
 * 8.0以上需要增加channel
 */
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannelIfNeeded() {
    if (Build.VERSION.SDK_INT >= 26) {
        val channel = NotificationChannel(NOTIFICATION_CHANNEL, "小米视频", NotificationManager.IMPORTANCE_LOW)
        channel.description = "下载"
        channel.enableLights(false)
        channel.enableVibration(false)
        //channel.importance = NotificationManager.IMPORTANCE_LOW //设置为low, 通知栏不会有声音
        mNotificationManager.createNotificationChannel(channel)
    }
}

猜你喜欢

转载自my.oschina.net/sfshine/blog/1791112