【问题标题】:Click action in push notification with firebase and react native点击带有firebase的推送通知中的操作并做出本机反应
【发布时间】:2018-10-02 11:08:29
【问题描述】:

我已经在我的应用程序上实现了推送通知及其工作。 现在当有人点击应用程序正在打开的通知时。

除此之外,当用户按下通知时,我想做另一件事:

1.向服务器发布请求(我想记录有人点击了通知)。

2。像现在一样打开应用

我的问题是我该怎么做?我需要在服务器端还是在本机端实现它? 如果有人有如何做到这一点的教程(适用于 android 和 iOS,甚至适用于其中一个),那将有很大帮助!

我找了很多,但没有找到可以帮助我的东西。

我正在添加我的工具:

在服务器端:

       public void sendNotification(String token,String msg)  {

    // This registration token comes from the client FCM SDKs.
    String registrationToken =token;

  // See documentation on defining a message payload.
    Message message = Message.builder()
            .setNotification(new com.google.firebase.messaging.Notification( null,msg))
            .setToken(registrationToken).setApnsConfig(ApnsConfig.builder().setAps(Aps.builder().setSound("default").build()).build()).setAndroidConfig(AndroidConfig.builder().setNotification(AndroidNotification.builder().setSound("default").build()).build())
            .build();

    try {
        String response = FirebaseMessaging.getInstance().send(message);
    } catch (FirebaseMessagingException e) {

    }
}

关于本机反应: 安卓系统:

 public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
    private static int count = 0;
@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
        Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
        Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
        String click_action= remoteMessage.getNotification().getClickAction();
//Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getTitle(),
                remoteMessage.getNotification().getBody(), remoteMessage.getData());
    }
//This method is only generating push notification
    private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
        PendingIntent contentIntent = null;
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                //.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(contentIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(count, notificationBuilder.build());
        count++;
    }
 }

在 iOS 上:

@implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
   NSURL *jsCodeLocation;
   jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
   [FIRApp configure];
   RCTRootView *rootView = [[RCTRootView alloc]  initWithBundleURL:jsCodeLocation
                                                  moduleName:@"**"
                                           initialProperties:nil
                                               launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  return YES;

    }

  // Required to register for notifications
  - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  {

    [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];

     }
 // Required for the register event.
   - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
     {
      [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
       }
 // Required for the notification event. You must call the completion handler after handling the remote notification.
  - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
                                                    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

  {
     [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    //NSLog(@"push-notification received: %@", notification)   
     }
  // Required for the registrationError event.
   - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  {
   [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
    }
  // Required for the localNotification event.
    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
   {
   [RCTPushNotificationManager didReceiveLocalNotification:notification];
    }

当我得到令牌时:

  setNotification(userid){

   const version =  DeviceInfo.getUniqueID()
      firebase.app().onReady().then(app => { 
      const again=  AsyncStorage.getItem('deviceToken', (err, token) =>  {
      this.props.profileActions.updateLoginTrack()
       console.log("checkingTokenFromLogin",token)
       console.log('version', version)
       if(token==null)    {
      console.log("tokenNull")

    app.messaging().getToken()
    .then(fcmToken => {
      if (fcmToken) {
          console.log('fcmtokenApp', fcmToken)
          this.saveDeviceToken(fcmToken)
          //need to save in database too
          let deviceTokenData = {
            userId:       userid,
            deviceUniqueId:        version,
            deviceToken:         fcmToken,
          }
          this.props.profileActions.updateDeviceToken(deviceTokenData)

      } else {
        console.log('error with getting token')
      } 
    })


  }

感谢您的帮助

【问题讨论】:

    标签: android ios react-native push-notification firebase-cloud-messaging


    【解决方案1】:

    解决方案:

    我找到的解决方案是

    right here

    我只使用了函数

    getInitialNotification()
    

    使用此功能,您可以在应用关闭时触发通知。

    如果您想在应用处于后台时触发通知,您需要使用此功能:

    onNotificationOpened()
    

    这个函数我没有使用监听器(它对我不起作用),我只在

    中使用了这个函数
    componentDidMount
    

    而不是在

    componentWillUnmount
    

    希望它能帮助某人并为您节省一些时间

    【讨论】:

    • 我有一个问题,我正在开发两个应用程序,首先是用户应用程序,其次是提供商,在用户应用程序中,我做了一些功能来发送订单并保存到实时数据库 firebase t 和在第二个应用程序中,我只是使用侦听器从数据库中检索数据,以便在不刷新应用程序的情况下实时获取新订单,所以当我从用户应用程序向 firebase 发送订单时,我想在其中显示通知第二个应用程序?如何处理这些
    • @DevAS 与 firebase 的一切都是关于配置和设备令牌的,您需要首先在两个应用程序中进行配置,然后将两个应用程序连接到 firebase 控制台。您需要两个应用程序都可以访问相同的数据库以获取设备令牌,您需要将设备令牌保存在登录到您的应用程序的用户的数据库中(此应用程序应该是您要发送通知的应用程序),在我的情况下,我从后端发送通知,但我很确定你可以从你的应用程序中做到这一点
    • @DevAS 如果您不知道如何使用 firebase 发送通知,您应该查看此链接:codementor.io/flame3/… 或 youtube 上的任何其他教程。希望它有所帮助:)
    • 我可以轻松做到这一点,但我的想法是我想将通知从应用程序发送到不在 firebase 控制台中的另一个应用程序!
    • @DevAS 我想我不知道该怎么做。我会建议你搜索它或打开一个新帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多