《第一行代码》第十章ServiceBestPractice出现错误:安卓开发8.1以上系统启动服务和通知报错

错误大致如下:Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification

原因:在8.0以前,安卓的通知是没有进行分类的,为了进一步优化管理通知,Google在发布android 8 时对通知做了修改优化,出现了通知渠道功能。具体原理可见:在Android 8.0中使用Notification中发生 Bad notification for startForeground错误

所以要加入通知渠道功能,在查阅资料,自己改了一下后可以调试通了,在此做个记录,待后面仔细学习。代码参考:android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException

需要改的部分:DownloadService->getNotification方法:

    private Notification getNotification(String title, int progress) {
        String CHANNEL_ONE_ID = "com.primedu.cn";
        String CHANNEL_ONE_NAME = "Channel One";
        //NotificationChannel notificationChannel = null;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"default");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                //修改安卓8.1以上系统报错
                     NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
                     notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
                     notificationChannel.setShowBadge(false);//是否显示角标
                     notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
                     NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    manager.createNotificationChannel(notificationChannel);
                    builder.setChannelId(CHANNEL_ONE_ID);
                    }
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        if (progress >= 0) {
            // 当progress大于或等于0时才需显示下载进度
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder.build();
    }

解释

  1. channelId
    通知渠道的ID:可以是任意的字符串,全局唯一就可以
  2. channelName
    通知渠道的名称,这个是用户可见的,开发者需要认真规划的命名

你可能感兴趣的:(Android)