Firebase(FCM):打开活动并传递有关通知点击的数据。安卓

时间:2016-10-21 16:40:38

标签: android firebase notifications firebase-realtime-database firebase-cloud-messaging

应明确实施如何使用Firebase通知和数据。我读了很多答案,但似乎无法使其发挥作用。这是我的步骤:

1。)我在PHP中将通知和数据传递给android,看起来很好:

$msg = array
    (
         "body" => $body,
         "title" => $title,
         "sound" => "mySound"
    );

    $data = array
    (

         "user_id" => $res_id,
         "date" => $date,
         "hal_id" => $hal_id,
         "M_view" => $M_view
    );

    $fields = array
    (
        'registration_ids' => $registrationIds,
        'notification' => $msg,
        'data' => $data
    );



    $headers = array
    (
        'Authorization: key='.API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec($ch );
    curl_close( $ch );

2。)在Android中收到通知和数据时,会显示通知。当我点击此通知时,它会打开应用程序。但我无法弄清楚应用程序打开时处理数据的方式。当app处于前景和后台时,存在几个不同之处。我现在的代码如下:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    String user_id = "0";
    String date = "0";
    String cal_id = "0";
    String M_view = "0";

    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        user_id = remoteMessage.getData().get("user_id");
        date = remoteMessage.getData().get("date");
        hal_id = remoteMessage.getData().get("hal_id");
        M_view = remoteMessage.getData().get("M_view");
    }

    //Calling method to generate notification
    sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
}

private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("fcm_notification", "Y");
    intent.putExtra("user_id", user_id);
    intent.putExtra("date", date);
    intent.putExtra("hal_id", hal_id);
    intent.putExtra("M_view", M_view);
    int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

3。)当我使用上面的代码时,当我点击通知时,所有它都会在后台打开应用程序。如果应用程序在前台然后通知点击它只是解除通知。但是,我希望在两种方案(后台和前台)中接收数据并打开特定的活动。我在MainActivity中有以下代码,但我无法获取数据。 fcm_notification,date,hal_id返回null。

public class MainActivity extends Activity {
 UserFunctions userFunctions;

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

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    Intent intent_o = getIntent();
}

@Override
protected void onResume() {
    super.onResume();
    userFunctions = new UserFunctions();
    if(userFunctions.isUserLoggedIn(getApplicationContext())){
        Intent intent_o = getIntent();
        String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
        String user_id = intent_o.getStringExtra("user_id");
        String date = intent_o.getStringExtra("date");
        String hal_id = intent_o.getStringExtra("hal_id");
        String M_view = intent_o.getStringExtra("M_view");
        Intent intent = new Intent(this, JobList.class);

        // THIS RETURNS NULL, user_id = null
        System.out.print("FCM" + user_id);
        startActivity(intent);
        finish();
    }else{
        // user is not logged in show login screen
        Intent login = new Intent(this, LoginActivity.class);
        startActivity(login);
        // Closing dashboard screen
        finish();
    }
}}

如果有人可以指导或建议如何从Firebase中检索MainActivity.java中的数据,无论是哪种情况(前景或背景)都很棒。

5 个答案:

答案 0 :(得分:31)

首先,我将介绍Handling Messages docs中提到的详细信息。

Both 行下的摘要中,它显示当应用程序位于前景时,有效负载将在您的{处理{1}}。

要从onMessageReceived()打开活动,您应检查所需数据是否在有效负载中,如果有,请调用您的特定活动,然后通过意图传递您需要的所有其他详细信息。

现在,如果应用程序位于后台,则会在文档中提及Android系统托盘收到通知,并且可以从onMessageReceived()有效内容>意图的额外内容。

只需添加我的回复here中的详细信息,其中几乎只提供了文档声明和示例链接:

  

处理背景应用中的通知消息

     

当您的应用在后台时,Android会将通知消息定向到系统托盘。用户点按通知会默认打开应用启动器。

     

这包括包含通知和数据有效负载的消息(以及从通知控制台发送的所有消息)。在这些情况下,通知会传送到设备的系统托盘,而数据有效负载会在启动器活动的附加内容中传送。

我认为@ArthurThompson的answer解释得非常好:

  

当您发送带有数据有效负载(通知和数据)的通知消息并且应用程序位于后台时,您可以从用户点击通知而启动的意图的附加内容中检索数据。

     

点击通知后,FCM sample启动MainActivity:

data

答案 1 :(得分:21)

在尝试所有答案后,博客提出了解决方案。如果有人需要请使用此视频作为参考

https://www.youtube.com/watch?v=hi8IPLNq59o

在视频中添加意图在MyFirebaseMessagingService中执行:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    String user_id = "0";
    String date = "0";
    String hal_id = "0";
    String M_view = "0";

    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        user_id = remoteMessage.getData().get("user_id");
        date = remoteMessage.getData().get("date");
        cal_id = remoteMessage.getData().get("hal_id");
        M_view = remoteMessage.getData().get("M_view");
    }

    String click_action = remoteMessage.getNotification().getClickAction();

    //Calling method to generate notification
    sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
}

private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
    Intent intent = new Intent(click_action);
    intent.putExtra("user_id", user_id);
    intent.putExtra("date", date);
    intent.putExtra("hal_id", hal_id);
    intent.putExtra("M_view", M_view);

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

并在onCreate或onResume中的新NotificationReceive活动中添加此

    notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
    user_id_text = (TextView) findViewById(R.id.user_id_text);

    Intent intent_o = getIntent();
    String user_id = intent_o.getStringExtra("user_id");
    String date = intent_o.getStringExtra("date");
    String hal_id = intent_o.getStringExtra("hal_id");
    String M_view = intent_o.getStringExtra("M_view");

    notification_Y_N.setText(date);
    user_id_text.setText(hal_id);

答案 2 :(得分:2)

要调用onMessageReceived()方法,您需要使用其他方法发送通知(例如创建Web API以发送通知)。然后使用它,

  

从您的FCM消息中删除通知有效内容,以便将数据有效负载传递到onMessageReceived()方法

当您的应用在后台时,仅当没有通知有效负载时,数据有效负载才会传递到onMessageReceived方法。

  

如果两个有效载荷都存在,那么系统会自动处理   通知部分(系统托盘)和您的应用程序获取数据有效负载   启动器活动的意图的额外内容(在用户点击之后   通知)。

欲了解更多信息,请参阅以下链接:

答案 3 :(得分:0)

您不需要自己实施sendNotificationonMessageReceived

发送时:

$data = array
(
    "user_id" => $res_id
    //whatever fields you want to include
);

$msg = array
(
     "body" => $body,
     "title" => $title,
     "data" => $data
     // more fields
);

android方面(在MainACtivity上:

private void handleIntent(Intent intent) {
    String user_id= intent.getStringExtra("user_id");
    if(user_id!= null)
        Log.d(TAG, user_id);
}

当然:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    handleIntent(intent);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    handleIntent(getIntent());
}

您放入data的任何字段都会发送到您的意图extra

答案 4 :(得分:0)

首先,如果您有响应中的数据对象和通知对象。然后要求后端开发人员删除通知对象。 我希望自己的班级能帮上忙。

public class MyFirebaseService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
   

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        Log.d(TAG, "Message data payload:id " + remoteMessage.getData().get("mode_id"));

      
        sendNotification(remoteMessage.getData().get("body"),
                remoteMessage.getData().get("mode_id"), remoteMessage.getData().get("click_action"));
        
    }
}

private void sendNotification(String messageBody, String id, String clickAction) {
    Intent intent = new Intent(clickAction);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(intent);
    intent.putExtra("id", id);
    intent.putExtra("body", messageBody);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent pendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "111")
            .setSmallIcon(R.drawable.venus_logo)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent)
            .setLights(Color.GREEN, 3000, 3000);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel("111", "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setShowBadge(false);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert notificationManager != null;
        notificationBuilder.setChannelId("111");
        notificationManager.createNotificationChannel(notificationChannel);
        notificationManager.notify(0, notificationBuilder.build());
    } else {
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(0, notificationBuilder.build());
    }
  }
}

然后将其添加到清单文件中。

    <service
        android:name=".data.services.MyFirebaseService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <activity
        android:name=".ui.notifications.NotificationsDetailsActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask"
        android:parentActivityName=".ui.home.HomeActivity"
        android:taskAffinity="">
        <intent-filter>
            <action android:name="co.example.yourApp.ui.notifications_TARGET_NOTIFICATION" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>