Как показать уведомление на Android 8+ - PullRequest
0 голосов
/ 23 сентября 2019

ПОЧЕМУ ЛЮДИ НЕ ПОМОГАЮТ МНЕ ???

В моем приложении я хочу показывать уведомление, и для этого я использовал службу сообщений FireBase.
Я пишу ниже коды под android 8 показывать уведомление, но выше android 8 не показывать никаких уведомлений!
Я знаю, что для показа уведомлений выше, чем android 8, я должен использовать ChannelID и я пишу кодыдля этого, но не показывать никаких уведомлений!

Класс MyNotificationManager:

public class MyNotificationManager {

    private Context mCtx;
    private Uri soundUri;
    private static MyNotificationManager mInstance;
    private Intent intent;
    private PendingIntent pendingIntent;
    private NotificationManager mNotifyMgr;

    public MyNotificationManager(Context context) {
        mCtx = context;
    }

    public static synchronized MyNotificationManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MyNotificationManager(context);
        }
        return mInstance;
    }

    public void displayNotification(String title, String body) {

        createNotificationChannel();

        // main initialize
        soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
        // Get General

        intent = new Intent(mCtx, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (mNotifyMgr != null) {
            mNotifyMgr.notify(0, getNotifyBuilder(title, body, pendingIntent).build());
        }

    }

    private NotificationCompat.Builder getNotifyBuilder(String title, String body, PendingIntent pendingIntent) {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, "utp_channel_1")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setSound(soundUri)
                .setPriority(Notification.PRIORITY_MAX)
                .setAutoCancel(true)
                .setContentText(body)
                .setContentIntent(pendingIntent);

        return mBuilder;
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "app_channel";
            String description = "app_channel_desc";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("app_channel_id", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = mCtx.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

Класс MyFireBaseMessagingService:

public class MyFireBaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        showNotify(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());

    }

    private void showNotify(String title, String body) {
        MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
        myNotificationManager.displayNotification(title, body);
    }
}

Манифест-коды:

</service>
<service android:name=".utility.firebase.MyFireBaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

Как это исправить?

Ответы [ 3 ]

0 голосов
/ 23 сентября 2019

Вы также должны попробовать это и сообщить мне:

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

        NotificationCompat.Builder mBuilder1 = new NotificationCompat.Builder(
                this, "my_channel_01").setSmallIcon(R.drawable.buy_gas)
                .setContentTitle(getString(R.string.app_name)).setContentText("Title goes here").setContentIntent(contentIntent);
        mBuilder1.setAutoCancel(true);


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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mBuilder1.setChannelId("my_channel_01");

            CharSequence name = "My New Channel";                   // The user-visible name of the channel.
            int importance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel channel = new NotificationChannel("my_channel_01", name, importance); //Create Notification Channel
            channel.setDescription("Channel description");
            mNotificationManager1.createNotificationChannel(channel);
        }

        mNotificationManager1.notify((int) System.currentTimeMillis(), mBuilder1.build());
0 голосов
/ 23 сентября 2019

В вашем классе FirebaseMessagingService вы обрабатываете только полезные данные уведомлений, а не данные.Если приложение находится в состоянии уничтожения и вы отправляете уведомление, оно не вызывает метод onReceive (), поэтому отправьте заголовок и сообщение с уведомлением в полезной нагрузке данных и сгенерируйте уведомление.

Попробуйте код ниже

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        //if messages contains data payload (map of custom key values)
         if(remoteMessage.getData().size() > 0){
            //handle the data message here           
            sendNotification(remoteMessage);
        }

        //if notification payload
        if (remoteMessage.getNotification() != null){          
            sendNotification(remoteMessage);
        }
    }


private void sendNotification(RemoteMessage remoteMessage){
         int notification_id = (int) System.currentTimeMillis();
         NotificationManager notificationManager = null;
         NotificationCompat.Builder mBuilder;

         String title = remoteMessage.getData().get("title");
         String body = remoteMessage.getData().get("body");
         String type = remoteMessage.getData().get("type");

         //Set pending intent to builder
         Intent intent = new Intent(getApplicationContext(), MainActivity.class);
         PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);

         //Notification builder
         if (notificationManager == null){
             notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         }


        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(CHANNEL_ID);
            if (mChannel == null){
                mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
                mChannel.setDescription(CHANNEL_DESCRIPTION);
                mChannel.enableVibration(true);
                mChannel.setLightColor(Color.GREEN);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(mChannel);
            }

            mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
            mBuilder.setContentTitle(title)
                    .setSmallIcon(R.drawable.ic_small)
                    .setContentText(body) //show icon on status bar
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setDefaults(Notification.DEFAULT_ALL);
        }else {
            mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setContentTitle(title)
                    .setSmallIcon(R.drawable.ic_small)
                    .setContentText(body)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setDefaults(Notification.DEFAULT_VIBRATE);
        }

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

Он будет работать как с Android 8+, так и ниже Android 8+.

0 голосов
/ 23 сентября 2019

Попробуйте этот метод

private void addNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("default", "Channel name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel description");
            notificationManager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
                .setSmallIcon(R.mipmap.notiicon)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setDefaults(Notification.DEFAULT_ALL)
                .setPriority(Notification.PRIORITY_HIGH)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setContentText("Your text.....");
        builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
    }
...