Уведомление не отображается после получения сообщения в Firebase Android
Я внедряю push-уведомление в своем приложении, используя firebase, отправляя данные с моего сервера для создания уведомлений, обрабатывая их вручную в службе намерений приложения, и это нормально работает в обоих случаях, когда приложение находится на переднем плане и в фоновом режиме. Но в случае, когда пользователь или система полностью удаляют мое приложение из диспетчера процессов или памяти, уведомление не отображается, когда в первый раз какая-либо полезная нагрузка данных, полученная с сервера после этого, даже onMessageReceived
Firebase называется и мой сервис намерений также вызывается из onMessageReceived
,
Это мой код получателя сообщений Firebase:
public class PushMessageHandler extends FirebaseMessagingService {
private final static String TAG = "PushMessageHandler";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
try {
Log.d(TAG, String.valueOf(remoteMessage.getData()));
Intent notificationService = new Intent(this, NotificationService.class);
notificationService.putExtra(Constants.NOTIFICATION_DATA,remoteMessage.getData()
.get(ResponseConstants.NOTIFICATION_DATA));
startService(notificationService);
} catch (Exception exe){
Crashlytics.logException(exe);
}
}
}
Код моего намерения:
@Override
protected void onHandleIntent(@Nullable Intent intent) {
try {
createPostNotification(new JsonObject(intent.getString(Constants.NOTIFICATION_DATA)));
} catch (Exception e){
Crashlytics.logException(e);
}
}
private void createPostNotification(JSONObject dataSets){
final String channelId = Constants.NOTIFICATION_CHANNEL_POST;
CharSequence name = getString(R.string.channel_name_post);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channelId,
name, NotificationManager.IMPORTANCE_DEFAULT);
mChannel.setLightColor(Color.GREEN);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
getNotificationManager().createNotificationChannel(mChannel);
}
final String mTitle;
final int noticeId = dataSets.getInt(ResponseConstants.POST_ID);
Intent resultIntent = new Intent(NotificationService.this, HomeActivity.class);
mTitle = dataSets.getString(ResponseConstants.POST_TITLE);
PostFeeds postFeeds = new PostFeeds();
postFeeds.setPostId(noticeId);
postFeeds.setPostBookmarked(false);
postFeeds.setPostTitle(mTitle);
postFeeds.setPostDate(dataSets.getInt(ResponseConstants.POST_DATE));
postFeeds.setPostLiked(false);
postFeeds.setPostLikes(0);
postFeeds.setPostFeaturedImage(dataSets.getString(ResponseConstants.POST_FEATURED_IMAGE));
resultIntent.putExtra(Constants.FEEDS,postFeeds);
resultIntent.putExtra(Constants.FEED_SOURCE, EventInitiator.NOTIFICATION);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
final PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), (int) System.currentTimeMillis()
, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final RemoteViews collapsedView = new RemoteViews(getPackageName(),
R.layout.notification_post_collapsed);
DateFormat dateFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
collapsedView.setTextViewText(R.id.postTitle, mTitle);
collapsedView.setTextViewText(R.id.timeStamp, dateFormat.format(new Date()));
Picasso.with(NotificationService.this)
.load(dataSets.getString(ResponseConstants.POST_FEATURED_IMAGE))
.priority(Picasso.Priority.HIGH)
.config(Bitmap.Config.ARGB_8888)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
RemoteViews expandedView;
expandedView = new RemoteViews(getPackageName(),
R.layout.notification_post_expanded);
expandedView.setTextViewText(R.id.postTitle, mTitle);
expandedView.setImageViewBitmap(R.id.postFeaturedImage, bitmap);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder notificationCompat =
new Notification.Builder(getApplicationContext(),channelId);
notificationCompat
.setSmallIcon(R.drawable.ic_stat_notify)
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setContentTitle(mTitle)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification = notificationCompat.build();
getNotificationManager().notify(noticeId, notification);
} else {
NotificationCompat.Builder notificationCompat =
new NotificationCompat.Builder(getApplicationContext(),channelId);
notificationCompat
.setSmallIcon(R.drawable.ic_stat_notify)
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setContentTitle(mTitle)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = notificationCompat.build();
getNotificationManager().notify(noticeId, notification);
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder notificationCompat =
new Notification.Builder(getApplicationContext(),channelId);
notificationCompat
.setSmallIcon(R.drawable.ic_stat_notify)
.setCustomContentView(collapsedView)
.setContentTitle(mTitle)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
Notification notification = notificationCompat.build();
getNotificationManager().notify(noticeId, notification);
} else {
NotificationCompat.Builder notificationCompat =
new NotificationCompat.Builder(getApplicationContext(),channelId);
notificationCompat
.setSmallIcon(R.drawable.ic_stat_notify)
.setCustomContentView(collapsedView)
.setContentTitle(mTitle)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = notificationCompat.build();
getNotificationManager().notify(noticeId, notification);
}
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
} catch (Exception e){
Crashlytics.logException(e);
}
}
Обновить
После некоторой отладки я получаю, что Picasso не возвращает растровое изображение, пока служба намерений не будет уничтожена. Как обработать здесь Пикассо так, чтобы он возвращал растровое изображение до прекращения обслуживания.
Я попробовал эту ссылку, IntentService Termination до того, как Picasso загрузит Bitmap, но не получится. Есть ли какой-либо метод или способ, кроме этого?