Firebase(FCM):打开活动并通过点击通知数据。安卓 [英] Firebase (FCM): open activity and pass data on notification click. android

查看:146
本文介绍了Firebase(FCM):打开活动并通过点击通知数据。安卓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该清楚地说明如何使用Firebase通知和数据。我读了很多答案,但似乎无法使其工作。这里是我的步骤︰

1。)我传递通知和数据到Android中的Android和它似乎是罚款:

$ msg =数组
b $ bsound=>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
);


$ b $ 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收到通知和数据时,会显示通知。当我点击这个通知它打开应用程序。但我无法弄清楚应用程序打开时处理数据的方式。应用程序在前台和后台时有几个不同之处。我现在的代码如下:

$ p $ public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG =MyFirebaseMsgService;

@Override
public void onMessageReceived(RemoteMessage remoteMessage){

String user_id =0;
String date =0;
字符串cal_id =0;
String M_view =0; (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);

$ b $ //调用方法生成通知
sendNotification(remoteMessage.getNotification().getBody(),user_id,date,hal_id,M_view);

$ b $ 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
保护无效的onNewIntent(意图意图){
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);
字符串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 {
//用户未登录显示登录屏幕
Intent login = new Intent(this,LoginActivity.class);
startActivity(login);
//关闭仪表板屏幕
finish();






如果任何人都可以指导或建议如何检索来自Firebase的MainActivity.java中的数据(前景或背景)都非常棒。

解决方案

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



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; (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();
$ b $ //调用方法生成通知
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_o = getIntent();
字符串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);


There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:

1.) I am passing notification and data to android in PHP and it seems to be fine:

$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.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:

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.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns 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();
    }
}}

IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.

解决方案

After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference

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

IN ADDITION to the video to add intents do in 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());
}}

and in new NotificationReceive activity in onCreate or onResume add this

    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);

这篇关于Firebase(FCM):打开活动并通过点击通知数据。安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆