简体   繁体   English

无法在后台和终止状态下触发推送通知

[英]Unable to trigger Push Notification in background and killed state

I am working on an app based on device to device push notifications. 我正在开发基于设备到设备的推送通知的应用程序。 My notifications are working fine when the app is in foreground. 当应用程序处于前台时,我的通知运行正常。 But it doesn't work as per requirement, when the app is in background or killed state. 但是当应用程序处于后台或已终止状态时,它无法按要求运行。 onMessageReceived() doesn't get called in that case. 在这种情况下,不会调用onMessageReceived() I have a custom notification which has two buttons (Accept and Reject). 我有一个具有两个按钮(接受和拒绝)的自定义通知。 When the app is in background or in killed state, I am able to get the notification, but the action buttons don't appear. 当应用程序处于后台或处于终止状态时,我可以收到通知,但不会显示操作按钮。 But when the app is in foreground, it works perfectly. 但是,当应用程序处于前台时,它可以完美运行。 Can you guys please help me this? 你们能帮我吗? I am stuck in this for long now. 我在这个问题上停留了很长时间。

Note: I am using FCM to generate push notifications. 注意:我正在使用FCM生成推送通知。 And the payload is in index.js file. 有效负载位于index.js文件中。 Payload contains both 'data' and 'notification', because notifications need to get generated in both Android and iOS. 有效负载包含“数据”和“通知”,因为需要同时在Android和iOS中生成通知。 I read somewhere that removing 'notification' from payload will make it work perfectly in foreground, background and killed state, and it does too, but that doesn't match my requirement as I need both 'data' and 'notifications'. 我在某处读到,从有效负载中删除“通知”将使其在前景,背景和被杀死状态下完美工作,而且也可以,但这与我的要求不符,因为我同时需要“数据”和“通知”。

Please help me out!! 请帮帮我!!

public class FirebaseNotifications extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String> remoteMessageData = remoteMessage.getData();

        String remoteMessageType = remoteMessageData.get(REMOTE_TYPE);

        /*E-Intercom Notification requires Users Action*/
        if (remoteMessageType.equals(getString(R.string.e_intercom))) {
            String message = remoteMessageData.get(REMOTE_MESSAGE);
            String profilePhoto = remoteMessageData.get(REMOTE_PROFILE_PHOTO);
            String notificationUID = remoteMessageData.get(REMOTE_NOTIFICATION_UID);
            String userUID = remoteMessageData.get(REMOTE_USER_UID);
            String visitorType = remoteMessageData.get(REMOTE_VISITOR_TYPE);
            String visitorMobileNumber = remoteMessageData.get(REMOTE_VISITOR_MOBILE_NUMBER);

            RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_custom_notification);

            remoteViews.setTextViewText(R.id.textNotificationMessage, message);

            /*We don't want to show Profile image if cabs and packages enter into society*/
            if (visitorType.equals(FIREBASE_CHILD_CABS) || visitorType.equals(FIREBASE_CHILD_PACKAGES)) {
                remoteViews.setViewVisibility(R.id.eIntercomProfilePic, View.GONE);
            } else {
                remoteViews.setImageViewBitmap(R.id.eIntercomProfilePic, getBitmapFromURL(profilePhoto));
            }

            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            String channelId;

            /*To support Android Oreo Devices and higher*/
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(
                        getString(R.string.default_notification_channel_id), getString(R.string.namma_apartments_channel), NotificationManager.IMPORTANCE_HIGH);
                Objects.requireNonNull(notificationManager).createNotificationChannel(mChannel);
                channelId = mChannel.getId();
                IntentFilter actionIntents = new IntentFilter();
                actionIntents.addAction(ACCEPT_BUTTON_CLICKED);
                actionIntents.addAction(REJECT_BUTTON_CLICKED);
                getApplicationContext().registerReceiver(new ActionButtonListener(), actionIntents);
            } else {
                channelId = getString(R.string.default_notification_channel_id);
            }

            Notification notification = new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.namma_apartment_notification)
                    .setContentTitle(NOTIFICATION_EXPAND_TITLE)
                    .setContentText(NOTIFICATION_EXPAND_MSG)
                    .setAutoCancel(true)
                    .setCustomBigContentView(remoteViews)
                    .setSound(RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND))
                    .setPriority(PRIORITY_DEFAULT)
                    .build();

            int mNotificationID = (int) System.currentTimeMillis();

            Intent acceptButtonIntent = new Intent(ACCEPT_BUTTON_CLICKED);
            acceptButtonIntent.putExtra(NOTIFICATION_ID, mNotificationID);
            acceptButtonIntent.putExtra(NOTIFICATION_UID, notificationUID);
            acceptButtonIntent.putExtra(USER_UID, userUID);
            acceptButtonIntent.putExtra(MESSAGE, message);
            acceptButtonIntent.putExtra(VISITOR_TYPE, visitorType);
            acceptButtonIntent.putExtra(VISITOR_PROFILE_PHOTO, profilePhoto);
            acceptButtonIntent.putExtra(VISITOR_MOBILE_NUMBER, visitorMobileNumber);
            PendingIntent acceptPendingIntent = PendingIntent.getBroadcast(this, 123, acceptButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.buttonAccept, acceptPendingIntent);

            Intent rejectButtonIntent = new Intent(REJECT_BUTTON_CLICKED);
            rejectButtonIntent.putExtra(NOTIFICATION_ID, mNotificationID);
            rejectButtonIntent.putExtra(NOTIFICATION_UID, notificationUID);
            rejectButtonIntent.putExtra(USER_UID, userUID);
            rejectButtonIntent.putExtra(VISITOR_TYPE, visitorType);
            PendingIntent rejectPendingIntent = PendingIntent.getBroadcast(this, 123, rejectButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.buttonReject, rejectPendingIntent);

            Objects.requireNonNull(notificationManager).notify(mNotificationID, notification);
        } else {

            /*General Notification - These do not require any user actions*/
            String message = remoteMessageData.get(REMOTE_MESSAGE);

            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            int mNotificationID = (int) System.currentTimeMillis();

            /*To support Android Oreo Devices and higher*/
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(
                        getString(R.string.default_notification_channel_id), getString(R.string.namma_apartments_channel), NotificationManager.IMPORTANCE_HIGH);
                Objects.requireNonNull(notificationManager).createNotificationChannel(mChannel);
            }
            /*After the Admin adds a notice and user receives notification, making sure user is navigated
             * to 'Notice Board' screen on press of notification in notification panel*/
            if (remoteMessageType.equals(getString(R.string.notice_board_notification))) {
                Intent noticeBoardIntent = new Intent(this, NoticeBoard.class);

                PendingIntent pendingIntent = PendingIntent.getActivity(this, Constants.NEW_NOTICE_CODE,
                        noticeBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                Notification noticeBoardNotification = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
                        .setSmallIcon(R.drawable.namma_apartment_notification)
                        .setAutoCancel(true)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(message)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setPriority(PRIORITY_DEFAULT)
                        .setContentIntent(pendingIntent)
                        .build();

                Objects.requireNonNull(notificationManager).notify(mNotificationID, noticeBoardNotification);
            } else {
                Notification notificationDefault = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
                        .setSmallIcon(R.drawable.namma_apartment_notification)
                        .setAutoCancel(true)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(message)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setPriority(PRIORITY_DEFAULT)
                        .build();

                Objects.requireNonNull(notificationManager).notify(mNotificationID, notificationDefault);

            }
        }
    }

    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return getCircleBitmap(myBitmap);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Bitmap getCircleBitmap(Bitmap bitmap) {
        final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(output);

        final int color = Color.RED;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawOval(rectF, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        bitmap.recycle();

        return output;
    }
}

For this purpose you can try this technique. 为此,您可以尝试此技术。 When you store FCM Token in DB add a bit or variable (device_type) in db that is used to store the device type like if FCM Token is come from IOS then add IOS in device_type and if it from android do this same for android device, then at the time of sending notification u can check if FCM Token is android type send just Data payload and if it is IOS type sent both Notification and Data Payload. 当您在数据库中存储FCM令牌时,请在db中添加用于存储设备类型的位或变量(device_type),例如FCM令牌来自IOS,然后在device_type中添加IOS,如果来自android,则对android设备执行相同操作,然后在发送通知时,您可以检查FCM令牌是否为android类型,仅发送数据有效载荷,以及是否为IOS类型,同时发送通知和数据有效载荷。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM