应用终止时的后台抓取react-native Android

问题描述

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

我已按照文档进行操作并实现了这样的操作

 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,您必须使用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