【问题标题】:How to handle notification data payload while app is in background?应用程序在后台时如何处理通知数据有效负载?
【发布时间】:2018-08-29 13:17:53
【问题描述】:

这是我的 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 问答,但没有任何帮助。我知道同类型的问题很多,但我没有从那里得到解决方案,所以我发布了这个问题。

【问题讨论】:

    标签: android firebase notifications firebase-cloud-messaging


    【解决方案1】:

    当您的应用处于后台时,Launcher 活动中会捕获 Intent。

    我在 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>
    

    【讨论】:

    • 好的,谢谢你的帮助,你能告诉我,如果我想从这个意图额外打开特定的活动,有可能吗?
    • 假设我想打开 Activity1 那么我应该将上面的代码粘贴到 Launcher Activity 还是 Activity1 的清单中?
    • 如果我想通过点击操作打开超过 1 个活动,是否可以在每个活动中放置意图过滤器?还是编码好?
    • 我想在不使用点击操作的情况下执行
    • 不,它只会打开一个活动,您在其中定义了操作。你可以做一件事,在通知和清单中区分点击动作。因此,当 action1 匹配时,它会跳转到 action2 和 activity2 以此类推。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多