FCM如何显示来自通知的数据点击另一个活动

时间:2017-05-14 11:49:21

标签: android firebase firebase-cloud-messaging

我有一个接收FCM通知的应用程序,我想在另一个活动中显示通知和数据有效负载的内容,我的挑战是当我点击通知时,它引导我进行欲望活动但我没有得到显示的信息。

请帮助,以下是我的代码

MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String> data = remoteMessage.getData();

        //you can get your text message here.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                String storedData = remoteMessage.getData().toString();
              //  JSONObject json = new JSONObject(storedData);

                JSONArray arr = new JSONArray(storedData);
                JSONObject jObj = arr.getJSONObject(0);
                String title = jObj.getString("title");
                String message = jObj.getString("body");
                sendPushNotification(jObj);

                final String MY_PREFS_NAME = "MyFCMFile";
                SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
                editor.putString("Title", title);
                editor.putString("Message", message);
                editor.apply();

            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
        else {

            String title = remoteMessage.getNotification().getTitle();
            String message = remoteMessage.getNotification().getBody();
            String click_action = remoteMessage.getNotification().getClickAction();
            Intent intent = new Intent(click_action);
            intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
            notificationBuilder.setContentTitle(title);
            notificationBuilder.setContentText(message);
            notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setContentIntent(pendingIntent);

            final String MY_PREFS_NAME = "MyFCMFile";
            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putString("Title", title);
            editor.putString("Message", message);
            editor.apply();

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notificationBuilder.build());


        }
    }

    //this method will display the notification
    //We are passing the JSONObject that is received from
    //firebase cloud messaging
    private void sendPushNotification(JSONObject json) {
        //optionally we can display the json into log
        Log.e(TAG, "Notification JSON " + json.toString());
        try {
            //getting the json data
            JSONObject data = json.getJSONObject("data");

            //parsing json data
            String title = data.getString("title");
            String message = data.getString("message");
            String imageUrl = data.getString("image");

            final String MY_PREFS_NAME = "MyFCMFile";

            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putString("Title", title);
            editor.putString("Message", message);
            editor.apply();

            //creating MyNotificationManager object
            MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());
            // CREATE CLICK ACTION

            //creating an intent for the notification

            Intent intent = new Intent(getApplicationContext(), Notifications.class);

            //if there is no image
            if (imageUrl.equals("null")) {
                //displaying small notification
                mNotificationManager.showSmallNotification(title, message, intent);
            } else {
                //if there is an image
                //displaying a big notification
                mNotificationManager.showBigNotification(title, message, imageUrl, intent);
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

我希望活动显示通知和数据有效负载信息-activity_notifications.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.Notifications">

    <FrameLayout
        android:layout_width="368dp"
        android:layout_height="551dp"
        android:orientation="vertical"
      >

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/job_notificatication" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="120dp"
            android:orientation="vertical">

            <LinearLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:background="@drawable/my_border"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="JOB INFO"
                    android:textStyle="bold" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Job Category :"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/category"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Job Type:"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/type"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Job Details:"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/details"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
               android:layout_marginTop="20dp"
                android:background="@drawable/my_border"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="CUSTOMER INFO"
                    android:textStyle="bold" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Name :"
                        android:textStyle="bold"
                     />
                    <TextView
                        android:id="@+id/name"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Address:"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/address"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Landmark"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/landmark"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Contact Person:"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/contact_person"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Expected Date"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/date"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Expected Time:"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/time"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textSize="36sp" />
                </LinearLayout>

            </LinearLayout>
            <Button
                android:id="@+id/accept"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="ACCEPT"/>
        </LinearLayout>
    </FrameLayout>

</android.support.constraint.ConstraintLayout>

Notifications.java

package com.example.workman;

import android.content.SharedPreferences;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Notifications extends AppCompatActivity {

    TextView title, message;

    String txtTitle, txtMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notifications);

        title = (TextView)findViewById(R.id.category);
        message = (TextView)findViewById(R.id.type);




    final String MY_PREFS_NAME = "MyFCMFile";
    SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
    String txtTitle = prefs.getString("Title", "");//"No name defined" is the default value.
    String txtMessage = prefs.getString("Message", "");//"No name defined" is the default value.

        title.setText(txtTitle);
        message.setText(txtMessage);
}
}

1 个答案:

答案 0 :(得分:1)

根据FCM文档,您看起来的方式是错误的。

只有在应用程序已在前台运行时,才会调用

onMessageReceived()

否则,Android将显示通知(使用“通知”字典的属性)并使用getClickAction()值打开所需的Activity,而无需编写任何代码。

您可以通过启动器活动的附加内容获取“数据”有效负载。

即。在Notifications课程中:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent ().getExtras (); // you should find the data here
    ...
}

这对我有用:

在我的第二个Activity课程中(点击通知时应该打开的课程)我把:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    TextView text    = (TextView) findViewById(R.id.data2);
    if (text != null) {
        Bundle extras = getIntent ().getExtras ();
        StringBuilder keys = new StringBuilder();
        if (extras != null) {
            for (String key : extras.keySet())
                keys.append(key + " = " + extras.getString(key) + "\n ");
        }
        text.setText("extras on second activity: " + keys.toString());
    }
} 

我得到了以下输出:

extras on second activity: google.sent_time = null
msg - some value (this is a key/value pair I included in the "data" dictionary)
uri - some value (this is a key/value pair I included in the "data" dictionary)
from - <the sender id>
google.message_id - <the message id returned in the receipt of the HTTP response>
collapse_key - com.package.fcmdemo (default value)

如您所见,我的(自定义)“数据”字典的属性都传递给了活动。 “通知”字典的属性未通过,但我认为这是故意的(因为它们已经用于显示我点击的通知以打开活动)。