La notification ne s'affiche pas dans Oreo


183

Normal Notification Builder n'affiche pas les notifications sur Android O.

Comment afficher une notification sur Android 8 Oreo?

Y a-t-il un nouveau morceau de code à ajouter pour afficher la notification sur Android O?


3
J'ai oublié de définir ".setChannelId" sur NotificationCompat.Builder et maintenant il fonctionne dans oreo (8.0)
varotariya vajsi

Réponses:


265

Dans Android O, il est indispensable d'utiliser un canal avec votre générateur de notifications

ci-dessous est un exemple de code:

// Sets an ID for the notification, so it can be updated.
int notifyID = 1; 
String CHANNEL_ID = "my_channel_01";// The id of the channel. 
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
            .setContentTitle("New Message")
            .setContentText("You've received new messages.")
            .setSmallIcon(R.drawable.ic_notify_status)
            .setChannelId(CHANNEL_ID)
            .build();

Ou avec la compatibilité Handling par:

NotificationCompat notification =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setChannelId(CHANNEL_ID).build();



NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
mNotificationManager.notify(notifyID , notification);

ou si vous voulez un correctif simple, utilisez le code suivant:

NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       mNotificationManager.createNotificationChannel(mChannel);
    }

Mises à jour: référence NotificationCompat.Builder

NotificationCompat.Builder(Context context)

Ce constructeur est obsolète au niveau d'API 26.0.0, vous devez donc utiliser

Builder(Context context, String channelId)

donc pas besoin setChannelIdavec le nouveau constructeur.

Et vous devez utiliser la dernière version de la bibliothèque AppCompat actuellement 26.0.2

compile "com.android.support:appcompat-v7:26.0.+"

Source de la chaîne des développeurs Android sur Youtube

En outre, vous pouvez consulter les documents Android officiels


4
Vous devez également créer un canal avant de pouvoir l'utiliser. Voir developer.android.com/reference/android/app/…
Guillaume Perrot

2
setChannel est obsolète au profit de setChannelId
Guillaume Perrot

1
Non, vous obtenez une erreur si vous ne créez pas de chaîne au moins une fois pendant la durée de l'installation de l'application.
Guillaume Perrot

1
@amorenew, apparemment, j'avais le mauvais nom de chaîne. Ça marche maintenant. Merci mais votre réponse n'est pas complète ... vous devez d'abord créer un canal en utilisant mNotificationManager.createNotificationChannel (mChannel); (J'ai fait cela dans ma classe d'application) ... voir google docs pour cela. Ajoutez peut-être ceci à votre réponse.
JPM

2
Quelles dépendances / versions dois-je cibler pour obtenir le nouveau NotificationCompat.Builder(Context, String)constructeur? J'utilise (entre autres): - compileSdkVersion 26- buildToolsVersion '26.0.2'- compile 'com.android.support:appcompat-v7:26.0.0-beta2' et pourtant il n'accepte toujours pas mon constructeur utilisant un contexte et une chaîne. Des idées?
Loisaida Sam Sandberg

94

Ici, je poste une fonction de solution rapide avec gestion de l'intention

public void showNotification(Context context, String title, String body, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = 1;
    String channelId = "channel-01";
    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.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addNextIntent(intent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
    );
    mBuilder.setContentIntent(resultPendingIntent);

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

Pareil ici. Un seul qui a fonctionné 4 moi pour FCM et Android> = 8.
YingYang

1
rapide et simple
alfian5229

Merci beaucoup. J'ai passé des heures à résoudre les problèmes de non-affichage des notifications. Donc, si vous voulez juste qu'une apparaisse, assurez-vous simplement d'avoir créé NotificationChannel à l'aide de NotificationManager pour Android Oreo +.
Joxon

ce code est le plus simple à implémenter et à comprendre, il est même à jour en décembre 2019. Merci.
Pradeep Dhawan

Quelle est la différence entre notificationManager.notify et startForeground sous Android?
user1090751

76

En plus de cette réponse , vous devez créer le canal de notification avant de pouvoir l'utiliser.

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

      /* Create or update. */
      NotificationChannel channel = new NotificationChannel("my_channel_01",
          "Channel human readable title", 
          NotificationManager.IMPORTANCE_DEFAULT);
      mNotificationManager.createNotificationChannel(channel);
  }

Vous devez également utiliser des canaux uniquement si votre targetSdkVersion est de 26 ou plus.

Si vous utilisez NotificationCompat.Builder, vous devez également mettre à jour vers la version bêta de la bibliothèque de support: https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0- beta2 (pour pouvoir appelersetChannelId au constructeur de compatibilité).

Soyez prudent car cette mise à jour de la bibliothèque élève minSdkLevel à 14.


Cela lèvera un avertissement si l'API min est inférieure à 26. Ajoutez @TargetApi (26) juste avant de créer le canal pour supprimer l'avertissement.
s-hunter

Si vous avez le if comme dans l'exemple de code, il ne produira pas d'avertissement, le correctif rapide a différentes suggestions, l'une d'elles consiste à entourer le code de la vérification de la version if. Si vous réglez la vérification de la version if, Android Studio peut être confus et ne pas le détecter.
Guillaume Perrot

11
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
    private NotificationChannel mChannel;
    private NotificationManager notifManager;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            try {
                JSONObject jsonObject = new JSONObject(remoteMessage.getData());
                displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void displayCustomNotificationForOrders(String title, String description) {
        if (notifManager == null) {
            notifManager = (NotificationManager) getSystemService
                    (Context.NOTIFICATION_SERVICE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder builder;
            Intent intent = new Intent(this, Dashboard.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent;
            int importance = NotificationManager.IMPORTANCE_HIGH;
            if (mChannel == null) {
                mChannel = new NotificationChannel
                        ("0", title, importance);
                mChannel.setDescription(description);
                mChannel.enableVibration(true);
                notifManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(this, "0");

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
            builder.setContentTitle(title)  
                    .setSmallIcon(getNotificationIcon()) // required
                    .setContentText(description)  // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setLargeIcon(BitmapFactory.decodeResource
                            (getResources(), R.mipmap.logo))
                    .setBadgeIconType(R.mipmap.logo)
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri
                            (RingtoneManager.TYPE_NOTIFICATION));
            Notification notification = builder.build();
            notifManager.notify(0, notification);
        } else {

            Intent intent = new Intent(this, Dashboard.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = null;

            pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(title)
                    .setContentText(description)
                    .setAutoCancel(true)
                    .setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
                    .setSound(defaultSoundUri)
                    .setSmallIcon(getNotificationIcon())
                    .setContentIntent(pendingIntent)
                    .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1251, notificationBuilder.build());
        }
    }

    private int getNotificationIcon() {
        boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
    }
}

Sans définir setChannelId (CHANNEL_ID) sur NotificationCompat.Builder, les notifications ne s'affichent pas.
Shihab Uddin

7

Si vous ne pouvez pas obtenir la notification push dans la version 26+ du SDK?

votre solution est ici:

public static void showNotification(Context context, String title, String messageBody) {

        boolean isLoggedIn = SessionManager.getInstance().isLoggedIn();
        Log.e(TAG, "User logged in state: " + isLoggedIn);

        Intent intent = null;
        if (isLoggedIn) {
            //goto notification screen
            intent = new Intent(context, MainActivity.class);
            intent.putExtra(Extras.EXTRA_JUMP_TO, DrawerItems.ITEM_NOTIFICATION);
        } else {
            //goto login screen
            intent = new Intent(context, LandingActivity.class);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        //Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        //Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);

        String channel_id = createNotificationChannel(context);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
                /*.setLargeIcon(largeIcon)*/
                .setSmallIcon(R.drawable.app_logo_color) //needs white icon with transparent BG (For all platforms)
                .setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
                .setVibrate(new long[]{1000, 1000})
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setContentIntent(pendingIntent)
                .setPriority(Notification.PRIORITY_HIGH)
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int) ((new Date(System.currentTimeMillis()).getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());
    }

public static String createNotificationChannel(Context context) {

        // NotificationChannels are required for Notifications on O (API 26) and above.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // The id of the channel.
            String channelId = "Channel_id";

            // The user-visible name of the channel.
            CharSequence channelName = "Application_name";
            // The user-visible description of the channel.
            String channelDescription = "Application_name Alert";
            int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
            boolean channelEnableVibrate = true;
//            int channelLockscreenVisibility = Notification.;

            // Initializes NotificationChannel.
            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
            notificationChannel.setDescription(channelDescription);
            notificationChannel.enableVibration(channelEnableVibrate);
//            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

            // Adds NotificationChannel to system. Attempting to create an existing notification
            // channel with its original values performs no operation, so it's safe to perform the
            // below sequence.
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            // Returns null for pre-O (26) devices.
            return null;
        }
    }

NotificationCompat.Builder notificationBuilder = nouveau NotificationCompat.Builder (contexte, channel_id)

-> Ici, vous obtiendrez une notification push en utilisant channel_idvotre appareil qui est composé de 26+ version SDK.

-> Parce que la NotificationCompat.Builder(context)méthode est obsolète, vous allez maintenant utiliser une version mise à jour qui a deux paramètres, l'un est context, l'autre est channel_id.

-> NotificationCompat.Builder(context, channel_id)méthode mise à jour. essayez-le.

-> Dans la version 26+ du SDK de l'appareil, vous créerez channel_id à chaque fois.


Merci J'utilisais un
notifcation_id

5

Utilisez cette classe pour la notification Android 8

public class NotificationHelper {

private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static final String NOTIFICATION_CHANNEL_ID = "10001";

public NotificationHelper(Context context) {
    mContext = context;
}

/**
 * Create and push the notification 
 */
public void createNotification(String title, String message)
{    
    /**Creates an explicit intent for an Activity in your app**/
    Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(resultPendingIntent);

    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
    {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
  }
}

4

Essayez ce code:

public class FirebaseMessagingServices extends com.google.firebase.messaging.FirebaseMessagingService {
    private static final String TAG = "MY Channel";
    Bitmap bitmap;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Utility.printMessage(remoteMessage.getNotification().getBody());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            String title = remoteMessage.getData().get("title");
            String body = remoteMessage.getData().get("body");
            String message = remoteMessage.getData().get("message");
            String imageUri = remoteMessage.getData().get("image");
            String msg_id = remoteMessage.getData().get("msg-id");
          

            Log.d(TAG, "1: " + title);
            Log.d(TAG, "2: " + body);
            Log.d(TAG, "3: " + message);
            Log.d(TAG, "4: " + imageUri);
          

            if (imageUri != null)
                bitmap = getBitmapfromUrl(imageUri);

            }

            sendNotification(message, bitmap, title, msg_id);
                    
        }


    }

    private void sendNotification(String message, Bitmap image, String title,String msg_id) {
        int notifyID = 0;
        try {
            notifyID = Integer.parseInt(msg_id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        String CHANNEL_ID = "my_channel_01";            // The id of the channel.
        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("message", message);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "01")
                .setContentTitle(title)
                .setSmallIcon(R.mipmap.ic_notification)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(message))
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setChannelId(CHANNEL_ID)
                .setContentIntent(pendingIntent);

        if (image != null) {
            notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle()   //Set the Image in Big picture Style with text.
                    .bigPicture(image)
                    .setSummaryText(message)
                    .bigLargeIcon(null));
        }


        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {       // For Oreo and greater than it, we required Notification Channel.
           CharSequence name = "My New Channel";                   // The user-visible name of the channel.
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name, importance); //Create Notification Channel
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());
    }

    public Bitmap getBitmapfromUrl(String imageUrl) {     //This method returns the Bitmap from Url;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            return bitmap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;

        }

    }

}


J'ai utilisé ce code mais chère notification avec Image n'est pas visible lorsque l'application en arrière-plan avez-vous une solution, veuillez aider.
Mohsin Khan

Cela dépend de certains facteurs tels que: - 1. Êtes-vous connecté au réseau .. ??? 2. L'URL de l'image est-elle correcte (vérifiez imageurl en cliquant sur imageurl sur le navigateur)
Rohit Mhatre

3

Application de démonstration de notification Android pour Android O ainsi que les versions d'API inférieures. Voici la meilleure application de démonstration sur GitHub-Demo 1 et GitHub-Demo 2 .

entrez la description de l'image ici


Veuillez envisager de publier un extrait de code minimal du fonctionnement de l'application au lieu de fournir des liens vers une source externe sans attribution / affiliation de l'identité du propriétaire des sources. (Ces sources peuvent également disparaître à tout moment sans autre moyen d'y accéder.)
Edric

2

Il s'agit d'un bogue dans la version 11.8.0 de l'API Firebase, donc si vous réduisez la version de l'API, vous ne serez pas confronté à ce problème.


En fait, je l'ai vérifié. Si vous travaillez sur l'émulateur Android, vérifiez votre application sur un appareil physique. Les nouveaux émulateurs n'apparaissent pas d'une manière ou d'une autre.
deadfish

Non, en fait, c'était en fait un bogue dans la version 11.8.0 de Firebase, et maintenant il est corrigé dans la nouvelle version 12.0.0. Pour référence, vous pouvez voir les notes de version officielles: firebase.google.com/support/release-notes/android
M.Noman

2

J'avais le même problème sur Oreo et j'ai découvert que si vous créez d'abord votre chaîne avec NotificationManager.IMPORTANCE_NONE, puis mettez-la à jour plus tard, la chaîne conservera le niveau d'importance d'origine.

Ceci est étayé par la documentation de formation Google Notification qui indique:

Une fois que vous avez créé un canal de notification, vous ne pouvez pas modifier les comportements de notification - l'utilisateur a un contrôle total à ce stade.

La suppression et la réinstallation de l'application vous permettront de réinitialiser les comportements de la chaîne.

Il est préférable d'éviter d'utiliser IMPORTANCE_NONE sauf si vous souhaitez supprimer les notifications pour ce canal, c'est-à-dire utiliser des notifications silencieuses.


1

Voici comment vous procédez

private fun sendNotification() {
    val notificationId = 100
    val chanelid = "chanelid"
    val intent = Intent(this, MainActivity::class.java)
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
        val name = "my channel"
        val description = "channel description"
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(chanelid, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }

    val mBuilder = NotificationCompat.Builder(this, chanelid)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Want to Open My App?")
            .setContentText("Open my app and see good things")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true) // cancel the notification when clicked
            .addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent

    val notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, mBuilder.build());
}

Lisez le didacticiel complet sur => https://developer.android.com/training/notify-user/build-notification


1

CHANNEL_IDdans NotificationChannel et Notification.Builder doivent être identiques, essayez ce code:

String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Solveta Unread", NotificationManager.IMPORTANCE_DEFAULT);


Notification.Builder notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID);

1

Eh bien, dans mon cas, j'ai Android 8.1.0 et le numéro de modèle vivo1811 , et j'ai essayé toutes les solutions ci-dessus mais rien ne fonctionne.

Donc, enfin, j'ai écrit au support Firebase puis sur un débogage plus poussé, j'obtenais ceci: "Échec de la diffusion vers l'application arrêtée": assurez-vous que l'application n'a pas été arrêtée de force " .

Et c'était la réponse de l'équipe Firebase ->

Il s'agit d'un problème connu causé par une optimisation de la batterie mise en œuvre par certains OEM. Lorsqu'une application est balayée dans le sélecteur d'application, l'application est traitée comme si elle avait été arrêtée de force, ce qui n'est pas le comportement par défaut d'Android. L'effet secondaire malheureux de ceci est que cela peut entraîner l'arrêt du service FCM de votre application. Nous travaillons à améliorer ce comportement de notre côté, mais le correctif doit venir du côté OEM.

Ici, OEM signifie fabricant d' équipement d'origine .


0

Pour toute personne aux prises avec cela après avoir essayé les solutions ci-dessus, assurez-vous que l'ID de canal utilisé lors de la création du canal de notification est identique à l'ID de canal que vous avez défini dans le générateur de notification.

const val CHANNEL_ID = "EXAMPLE_CHANNEL_ID"

// create notification channel
val notificationChannel = NotificationChannel(CHANNEL_ID, 
NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH)

// building notification
NotificationCompat.Builder(context)
                    .setSmallIcon(android.R.drawable.ic_input_add)
                    .setContentTitle("Title")
                    .setContentText("Subtitle")   
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setChannelId(CHANNEL_ID)

0
private void addNotification() {
                NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("Notifications Example")
                .setContentText("This is a test notification");
                Intent notificationIntent = new Intent(this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent);
                // Add as notification
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
                {
                NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
                nChannel.enableLights(true);
                assert manager != null;
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
                manager.createNotificationChannel(nChannel);
                }
                assert manager != null;
                manager.notify(0, builder.build());
    }

0

La méthode suivante affichera la notification , avec le gros texte et le gel activés (la notification ne sera pas supprimée même après les balayages de l'utilisateur). Nous avons besoin du service NotificationManager

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

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder notificationBuilder = new Notification.Builder(context)
                .setContentTitle(title + DateFormat.getDateTimeInstance().format(new Date()) + ":" + accuracy)
                .setContentText(addressFragments.toString())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(contentIntent)
                .setOngoing(true)
                .setStyle(new Notification.BigTextStyle().bigText(addressFragments.toString()))
                .setAutoCancel(true);
        notificationManager.notify(3, notificationBuilder.build());
}

Méthode pour supprimer les notifications

public static void removeNotification(Context context){
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

Lien source


0
NotificationCompat.Builder(Context context)

déjà obsolète pour la version supérieure ou égale à Android Oreo. Vous pouvez modifier l'implémentation en utilisant

NotificationCompat.Builder(Context context, String channelId)

0
fun pushNotification(message: String?, clickAtion: String?) {
        val ii = Intent(clickAtion)
        ii.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE, ii, PendingIntent.FLAG_ONE_SHOT)

        val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        val largIcon = BitmapFactory.decodeResource(applicationContext.resources,
                R.mipmap.ic_launcher)


        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val channelId = "default_channel_id"
        val channelDescription = "Default Channel"
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            var notificationChannel = notificationManager.getNotificationChannel(channelId)
            if (notificationChannel != null) {
                val importance = NotificationManager.IMPORTANCE_HIGH //Set the importance level
                notificationChannel = NotificationChannel(channelId, channelDescription, importance)
               // notificationChannel.lightColor = Color.GREEN //Set if it is necesssary
                notificationChannel.enableVibration(true) //Set if it is necesssary
                notificationManager.createNotificationChannel(notificationChannel)


                val noti_builder = NotificationCompat.Builder(this)
                        .setContentTitle("MMH")
                        .setContentText(message)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setChannelId(channelId)
                        .build()
                val random = Random()
                val id = random.nextInt()
                notificationManager.notify(id,noti_builder)

            }

        }
        else
        {
            val notificationBuilder = NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher).setColor(resources.getColor(R.color.colorPrimary))
                    .setVibrate(longArrayOf(200, 200, 0, 0, 0))
                    .setContentTitle(getString(R.string.app_name))

                    .setLargeIcon(largIcon)
                    .setContentText(message)
                    .setAutoCancel(true)
                    .setStyle(NotificationCompat.BigTextStyle().bigText(message))
                    .setSound(soundUri)
                    .setContentIntent(pendingIntent)


            val random = Random()
            val id = random.nextInt()
            notificationManager.notify(id, notificationBuilder.build())

        }



    }

1
Bien que cet extrait de code puisse résoudre le problème, il n'explique pas pourquoi ni comment il répond à la question. Veuillez inclure une explication de votre code , car cela contribue vraiment à améliorer la qualité de votre message. N'oubliez pas que vous répondez à la question aux lecteurs à l'avenir, et que ces personnes pourraient ne pas connaître les raisons de votre suggestion de code. Vous pouvez utiliser le bouton Modifier pour améliorer cette réponse afin d'obtenir plus de votes et de réputation!
Brian Tompsett - 汤 莱恩

0

Le morceau de code ci-dessous fonctionne pour moi dans l'Oreo, vous pouvez essayer ceci. j'espère que cela fonctionnera pour vous

private void sendNotification (Context ctx, String title, int notificationNumber, String message, String subtext, Intent intent) {
try {

            PendingIntent pendingIntent = PendingIntent.getActivity(ctx, notificationNumber, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            Uri url = null;           
            NotificationCompat.Builder notificationBuilder = null;
            try {
                if (Build.VERSION.SDK_INT >= 26) {

                    try{
                        NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.deleteNotificationChannel(CHANNEL_ID_1);
                        notificationManager.deleteNotificationChannel(CHANNEL_ID_2);

                        if(!intent.getStringExtra("type").equalsIgnoreCase(""+TYPE_REQUEST)){
                            NotificationChannel breaking = new NotificationChannel(CHANNEL_ID_1, CHANNEL_ID_1_NAME, NotificationManager.IMPORTANCE_HIGH);
                            breaking.setShowBadge(false);
                            breaking.enableLights(true);
                            breaking.enableVibration(true);
                            breaking.setLightColor(Color.WHITE);
                            breaking.setVibrationPattern(new long[]{100, 200, 100, 200, 100, 200, 100});
                            breaking.setSound(url,new AudioAttributes.Builder().build());

                            notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID_1)
                                    .setSmallIcon(R.mipmap.ic_launcher);
                            notificationManager.createNotificationChannel(breaking);

                        }else{

                            NotificationChannel politics = new NotificationChannel(CHANNEL_ID_2,CHANNEL_ID_2_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                            politics.setShowBadge(false);
                            politics.enableLights(true);
                            politics.enableVibration(true);
                            politics.setLightColor(Color.BLUE);
                            politics.setVibrationPattern(new long[]{100, 200, 100, 200, 100});
                            politics.setSound(url,new AudioAttributes.Builder().build());

                            notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID_2)
                                    .setSmallIcon(R.mipmap.ic_launcher);
                            notificationManager.createNotificationChannel(politics);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                } else {
                    notificationBuilder = new NotificationCompat.Builder(ctx)
                            .setSmallIcon(R.mipmap.ic_launcher);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (notificationBuilder == null) {
                notificationBuilder = new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.mipmap.ic_launcher);
            }


            notificationBuilder.setContentTitle(title);          
            notificationBuilder.setSubText(subtext);
            notificationBuilder.setAutoCancel(true);

            notificationBuilder.setContentIntent(pendingIntent);
            notificationBuilder.setNumber(notificationNumber);
            NotificationManager notificationManager =
                    (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(notificationNumber, notificationBuilder.build());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

0

Dans Android Oreo, l'application de notification est effectuée à l'aide de canaux et de la classe NotificationHelper.Il doit avoir un identifiant et un nom de canal.

Vous devez d'abord créer une classe NotificationHelper

public class NotificationHelper extends ContextWrapper {

private static final String EDMT_CHANNEL_ID="com.example.safna.notifier1.EDMTDEV";
private static final String EDMT_CHANNEL_NAME="EDMTDEV Channel";
private NotificationManager manager;

public  NotificationHelper(Context base)
{
    super(base);
    createChannels();
}
private void createChannels()
{
    NotificationChannel edmtChannel=new NotificationChannel(EDMT_CHANNEL_ID,EDMT_CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT);
    edmtChannel.enableLights(true);
    edmtChannel.enableVibration(true);
    edmtChannel.setLightColor(Color.GREEN);
    edmtChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

    getManager().createNotificationChannel(edmtChannel);

}
public NotificationManager getManager()
{
   if (manager==null)
       manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
   return manager;

}
public NotificationCompat.Builder getEDMTChannelNotification(String title,String body)
{
    return new NotificationCompat.Builder(getApplicationContext(),EDMT_CHANNEL_ID)
            .setContentText(body)
            .setContentTitle(title)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setAutoCancel(true);
    }
}

Créez un bouton dans le fichier xml d'activité, puis Dans l'activité principale

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    helper=new NotificationHelper(this);

    btnSend=(Button)findViewById(R.id.btnSend);

    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String title="Title";
            String content="Content";
            Notification.Builder builder=helper.getEDMTChannelNotification(title,content);
            helper.getManager().notify(new Random().nextInt(),builder.build());
        }
    });

}

Puis lancez votre projet


0

Vous devez créer un canal de notification pour le niveau d'API supérieur à 26 (oreo).

`NotificationChannel channel = new NotificationChannel(STRING_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);

STRING_ID = string notification channelid est le même que dans Notification.Builder comme ceci

`Notification notification = new Notification.Builder(this,STRING_ID)
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();`

L'identifiant de canal dans la notification et dans la notification doit être le même. Le code entier est comme ça .. `

@RequiresApi(api = Build.VERSION_CODES.O)
  private void callNotification2() {

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,11, 
    intent,PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(this,"22")
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();
    NotificationChannel channel = new 
    NotificationChannel("22","newName",NotificationManager.IMPORTANCE_HIGH);
    NotificationManager manager = (NotificationManager) 
    getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
    manager.notify(11,notification);

    }'

0

Tout d'abord, si vous ne savez pas, depuis Android Oreo, c'est-à-dire le niveau d'API 26, il est obligatoire que les notifications soient renvoyées avec un canal.

Dans ce cas, de nombreux didacticiels peuvent vous dérouter car ils montrent des exemples différents pour la notification au-dessus de oreo et en dessous.

Voici donc un code commun qui fonctionne à la fois au-dessus et au-dessous de oreo:

String CHANNEL_ID = "MESSAGE";
String CHANNEL_NAME = "MESSAGE";

NotificationManagerCompat manager = NotificationManagerCompat.from(MainActivity.this);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
    NotificationManager.IMPORTANCE_DEFAULT);
    manager.createNotificationChannel(channel);
}

Notification notification = new NotificationCompat.Builder(MainActivity.this,CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_android_black_24dp)
        .setContentTitle(TitleTB.getText().toString())
        .setContentText(MessageTB.getText().toString())
        .build();
manager.notify(getRandomNumber(), notification); // In case you pass a number instead of getRandoNumber() then the new notification will override old one and you wont have more then one notification so to do so u need to pass unique number every time so here is how we can do it by "getRandoNumber()"
private static int getRandomNumber() {
    Date dd= new Date();
    SimpleDateFormat ft =new SimpleDateFormat ("mmssSS");
    String s=ft.format(dd);
    return Integer.parseInt(s);
}

Didacticiel vidéo: VIDEO YOUTUBE

Si vous souhaitez télécharger cette démo: Lien GitHub


-1
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID")
            ........

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Hello";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mNotificationManager.createNotificationChannel(mChannel);
    }
    mNotificationManager.notify(notificationId, notificationBuilder.build());
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.