Уведомление получено, но данные не сохраняются, когда приложение закрыто или экран выключен [закрыто]Android

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Уведомление получено, но данные не сохраняются, когда приложение закрыто или экран выключен [закрыто]

Сообщение Anonymous »

Код: Выделить всё

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyApp::MyWakelockTag");
wakeLock.acquire(10*60*1000L /*10 minutes*/);

try {
String body = null;
String title = null;
String imageUrl = null;

if (remoteMessage.getNotification() != null) {
body = remoteMessage.getNotification().getBody();
title = remoteMessage.getNotification().getTitle();
imageUrl = remoteMessage.getData().get("image");
} else if (!remoteMessage.getData().isEmpty()) {
body = remoteMessage.getData().get("message");
title = remoteMessage.getData().get("title");
imageUrl = remoteMessage.getData().get("image");
}
String time = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

sendNotification(title, body, imageUrl);
saveNotificationWithWorkManager(title, body, imageUrl, time);

} finally {
wakeLock.release();
}
}

private void saveNotificationWithWorkManager(String title, String body, String imageUrl, String time) {
Data notificationData = new Data.Builder()
.putString("title", title)
.putString("body", body)
.putString("imageUrl", imageUrl)
.putString("time", time)
.build();

OneTimeWorkRequest saveNotificationWork = new OneTimeWorkRequest.Builder(SaveNotificationWorker.class)
.setInitialDelay(5, TimeUnit.SECONDS)  // Optional delay
.setInputData(notificationData)
.build();

WorkManager.getInstance(this).enqueue(saveNotificationWork);
}

private void sendNotification(String messageBody, String title, String imageUrl) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

String channelId = "fcm_default_channel";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

if (imageUrl != null &&  !imageUrl.isEmpty()) {
Bitmap bitmap = getBitmapFromURL(imageUrl);
if (bitmap != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));
}
}

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

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}

notificationManager.notify(0, notificationBuilder.build());
}
private Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
return null;
}
}
}
Когда экран телефона выключен или когда приложение закрыто, уведомление приходит через Firebase, но данные уведомления не сохраняются в автономной базе данных. Я хочу, чтобы уведомление сохранялось в базе данных сразу по его прибытии, но оно работает только тогда, когда приложение открыто.
Я пробовал игнорировать WorkManager, службу переднего плана и оптимизацию батареи, но не могу найти решение. Надеюсь, кто-нибудь сможет мне помочь.

Подробнее здесь: https://stackoverflow.com/questions/790 ... screen-off
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»