web-dev-qa-db-fra.com

Notification Android non affichée sur l'API 26

J'ai récemment mis à jour mon application vers l'API 26 et les notifications ne fonctionnent plus, sans même changer le code.

val notification = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Title")
                .setContentText("Text")
                .build()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notification)

Pourquoi ça ne marche pas? Y a-t-il eu des changements dans l'API dont je ne suis pas au courant?

8
Aaron

De la documentation :

Android O introduit des canaux de notification pour fournir un système unifié permettant aux utilisateurs de gérer les notifications. Lorsque vous ciblez Android O, vous devez implémenter un ou plusieurs canaux de notification pour afficher les notifications destinées à vos utilisateurs. Si vous ne ciblez pas Android O, vos applications se comportent de la même manière que sur Android 7.0 lorsqu'elles s'exécutent sur des appareils Android O. 

(emphase ajoutée)

Vous ne semblez pas associer cette Notification à un canal.

15
CommonsWare

Ici je poste une solution rapide 

public void notification(String title, String message, Context context) { 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = createID();
    String channelId = "channel-id";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (Android.os.Build.VERSION.SDK_INT >= Android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.app_logo)//R.mipmap.ic_launcher
            .setContentTitle(title)
            .setContentText(message)
            .setVibrate(new long[]{100, 250})
            .setLights(Color.YELLOW, 500, 5000)
            .setAutoCancel(true)
            .setColor(ContextCompat.getColor(context, R.color.colorPrimary));

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addNextIntent(new Intent(context, MainAcivity.class));
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    notificationManager.notify(notificationId, mBuilder.build());
}

public int createID() {
    Date now = new Date();
    int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.FRENCH).format(now));
    return id;
}
2
Sofiane Majdoub