Android O - Single line Notification - like the “Android System - USB charging this device”

前端 未结 4 1203
难免孤独
难免孤独 2020-12-14 15:57

I would like to have an ongoing notification for my ForegroundService that requires as small place as possible. I like the "Android System - USB charging t

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 16:31

    You need to set the Notification priority to Min, the Notification Channel importance to Min, and disable showing the Notification Channel Badge.

    Here's a sample of how I do it. I've included creating the full notification as well for reference

    private static final int MYAPP_NOTIFICATION_ID= -793531;
    
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    
    String CHANNEL_ID = "myapp_ongoing";
    CharSequence name = context.getString(R.string.channel_name_ongoing);
    
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_MIN);
        channel.setShowBadge(false);
    
        notificationManager.createNotificationChannel(channel);
    }
    
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_stat_notification_add_reminder)
            .setContentTitle(context.getString(R.string.app_name))
            .setContentText(context.getString(R.string.create_new))
            .setOngoing(true).setWhen(0)
            .setChannelId(CHANNEL_ID)
            .setPriority(NotificationCompat.PRIORITY_MIN);
    
    // Creates an intent for clicking on notification
    Intent resultIntent = new Intent(context, MyActivity.class);
    ...
    
    // The stack builder object will contain an artificial back stack
    // for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out
    // of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MyActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    
    notificationManager.notify(MYAPP_NOTIFICATION_ID, mBuilder.build());
    

提交回复
热议问题