Я работаю над приложением на основе push-уведомлений от устройства к устройству.Мои уведомления работают нормально, когда приложение находится на переднем плане.Но это не работает в соответствии с требованием, когда приложение находится в фоновом или отключенном состоянии.onMessageReceived()
не вызывается в этом случае.У меня есть пользовательское уведомление, которое имеет две кнопки (Принять и Отклонить).Когда приложение работает в фоновом режиме или отключено, я могу получить уведомление, но кнопки действий не отображаются.Но когда приложение находится на переднем плане, оно работает отлично.Ребята, не могли бы вы помочь мне с этим?Я застрял в этом надолго.
Примечание. Я использую FCM
для создания push-уведомлений.И полезная нагрузка находится в файле index.js.Полезная нагрузка содержит как «данные», так и «уведомления», потому что уведомления должны генерироваться как в Android, так и в iOS.Я где-то читал, что удаление «уведомления» из полезной нагрузки сделает его отлично работающим на переднем плане, в фоновом и отключенном состоянии, и это тоже так, но это не соответствует моим требованиям, так как мне нужны и «данные», и «уведомления».
Пожалуйста, помогите мне !!
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;
}
}