android 8.1 在设置前台服务时, 发送通知, 需要指定一个 channelId;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
private void startForeground() { String channelId =""; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { channelId=createNotificationChannel(); } Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity (this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId ); Notification notification = notificationBuilder.setOngoing(true) .setSmallIcon(R.drawable.icon) .setContentTitle("我的工具") .setContentText("内容") .setContentIntent(pendingIntent) .setPriority(PRIORITY_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(101, notification); } @RequiresApi(Build.VERSION_CODES.O) private String createNotificationChannel(){ String channelId = "mx_service"; String channelName = "mx_service_name"; NotificationChannel chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH); chan.setLightColor(Color.BLUE); chan.setImportance(NotificationManager.IMPORTANCE_NONE); chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); service.createNotificationChannel(chan); return channelId; } |
0 Comments