Как обрабатывать полезные данные уведомлений, когда приложение находится в фоновом режиме? - PullRequest
0 голосов
/ 29 августа 2018

Вот мой MyFirebaseMessagingService.class

public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() { }
DataBaseUtil dataBaseUtil = null;

String sname;
Intent intent= new Intent();
String orderId;
String strmessage,strmsgtext;

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    dataBaseUtil = new DataBaseUtil();
    if (remoteMessage.getNotification() != null) {
        L.e( "Message Notification Body: " + remoteMessage.getNotification().getBody());
        RemoteMessage.Notification fcm = remoteMessage.getNotification();
        PojoNotification pojo = new PojoNotification();
        pojo.setTitle(fcm.getTitle());
        pojo.setContent(fcm.getBody());

       Map<String, String> dataMap = remoteMessage.getData();            

       orderId = dataMap.get("orderId").toString().trim();
       sname = dataMap.get("screen_name").toString().trim();
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }
        pojo.setId(new Random().nextInt(9000));
        dataBaseUtil.insertNotification(pojo);
        if (SP.getBoolean(SP.LOGIN) ){
            showNotification(pojo);
        }
        else {
        }
    }else {
        L.e( "Message Notification Body: " + "abcv");

    }
}

А вот мой метод showNotification:

 void showNotification(PojoNotification pojo) {

    intent= new Intent(getApplicationContext(),MainActivity.class);
   intent.putExtra("screen_name", sname);
 //  intent.putExtra(Constance.id,pojo.getId());
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("default",
                "SGrip",
                NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
        mNotificationManager.createNotificationChannel(channel);

    }
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "default")
            .setSmallIcon(R.mipmap.ic_launcher) // notification icon

            .setContentTitle(pojo.getTitle()) // title for notification
            .setContentText(pojo.getContent())// message for notification
          //  .setSound(alarmSound) // set alarm sound for notification

            .setAutoCancel(true); // clear notification after click

    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pi);
    mNotificationManager.notify(0, mBuilder.build());


}

Здесь я получаю весь фон уведомлений и передний план, но проблема, с которой я сталкиваюсь, заключается в том, что, когда мое приложение находится в фоновом режиме, данные полезной нагрузки данных не извлекаются, а когда мое приложение находится на переднем плане, все данные получают как требуется

Здесь, моя деятельность по запуску, где я получаю дополнительные намерения

   if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            String value = getIntent().getExtras().getString(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
        }
    }

а вот код уведомления со стороны сервера

    {
 "registration_ids" : ["cFxiduH5j9I:APA91bEFAYPOR57yDga8urRuhmPuj_CI9h-bIyEwCcQeyFsvnFU_Nh9zkTmQVE7oiwdXchvIIz4DmUW1nqIOslBg_3oV7cWDZBjwb7WFqQ3E4RZ2T2vXCFN6IQ_1pBIfL67pHwthEZA4"],
 "notification" : {
     "title" : "First Notification",
     "text": "Collapsing A",
     "sound":"default"
 },
 "data" : {
     "screen_name" : "acc_screen"
 }
}

Я прочитал много уроков, много вопросов и ответов по stackoverflow, но ничто не помогло мне. Я знаю, что вопросов такого же типа много, но я не могу найти решение, поэтому я отправил вопрос.

1 Ответ

0 голосов
/ 29 августа 2018

Когда ваше приложение находится в фоновом режиме, намерение поймано в активности Launcher.

Я реализовал то же самое в Kotlin, пожалуйста, обратитесь:

 val bundle = intent.extras
    if (bundle != null) {
        val notificationModel = NotificationModel()
        try {
            val target = Target()
            if (bundle.containsKey("view"))
                target.view = bundle.getString("view")
            if (bundle.containsKey("circle_id"))
                target.circleId = bundle.getString("circle_id")
            if (bundle.containsKey("user_id"))
                target.userId = bundle.getString("user_id")
            if (bundle.containsKey("group_id"))
                target.groupId = bundle.getString("group_id")
            if (bundle.containsKey("file_id"))
                target.fileId = bundle.getString("file_id")

            notificationModel.target = target
        } catch (ex: JSONException) {
            ex.printStackTrace()
        }
    }

Обновлено

Когда ваше приложение находится в фоновом режиме и нажимает на уведомление, запускается программа запуска по умолчанию. Чтобы запустить желаемое действие, вам нужно указать click_action в вашем уведомлении.

$noti = array
(
'icon' => 'new',
'title' => 'title',
'body' => 'new msg',
'click_action' => 'your activity name comes here'
); 

А в вашем android.manifest файле

Добавьте следующий код, где вы зарегистрировали свою деятельность

 <activity
            android:name="your activity name">
            <intent-filter>
                <action android:name="your activity name" />
               <category android:name="android.intent.category.DEFAULT"/>
           </intent-filter>

...