【问题标题】:Background fetch when app is terminated react-native Android应用程序终止时的后台获取 react-native Android
【发布时间】:2021-01-14 05:49:46
【问题描述】:

我已经在互联网上搜索了很长时间,但在任何地方都找不到合适的文档来在应用程序终止时(不在后台)实现后台提取。

我已经按照文档进行了这样的实现:

 useEffect(() => {
    BackgroundFetch.configure(
      {
        forceAlarmManager: true,
        enableHeadless: true,
        stopOnTerminate: false,
        requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY,
        startOnBoot: true,
      },
      async (taskId) => {
        console.log('[BackgroundFetch] taskId: ', taskId);

        PushNotification.localNotificationSchedule({
          bigText:
            'We will be watering your Plants in few minutes. Please check if your schedule is updated in Device',
          subText: 'Background task',
          title: 'Watering Plants',
          color: '#60ad5e',
          message: 'Expand to show more',
          actions: ['Okay'],
          group: 'group',
          date: new Date(Date.now() + 5 * 1000), //Change this to (scheduled time - some minutes) as to notify the user earlier.
        });

        BackgroundFetch.finish(taskId);
      },
    );
   
  }, []);


// And with with #scheduleTask
  BackgroundFetch.scheduleTask({
    taskId: 'com.foo.customtask',
    delay: 15000, // milliseconds
    forceAlarmManager: true,
    periodic: false,
  });

所以这里基本上我想运行 API 获取并向用户显示推送通知。所以用户有可能从后台删除应用程序(即他终止)。 因此,即使应用程序在 ANDROID 中终止,我也想显示此推送通知。

谁能告诉我我在这里做错了什么?

【问题讨论】:

    标签: android react-native fetch-api terminate background-fetch


    【解决方案1】:

    对于 Android,您必须使用 firebase 发送推送通知。 我强烈推荐 @react-native-firebase 应用程序及其文档。

    基本上,在您完成安装后,代码就是

    import messaging from '@react-native-firebase/messaging';                                            
                                                                                                     
    // Register background handler                                                                       
    messaging().setBackgroundMessageHandler(async remoteMessage => {                                     
      console.log('Message handled in the background!', remoteMessage);                                  
    });                                                                                                  
                                                                                                     
    AppRegistry.registerComponent(appName, () => App);
    

    在 index.js 中

    查看他们的 firebase 应用文档 https://rnfirebase.io/

    还有消息传递部分 https://rnfirebase.io/messaging/usage

    【讨论】:

    • 谢谢你,我会检查一下!
    • 接受此答案,因为实现此目的的唯一方法是使用远程推送通知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多