react本机推送通知不会在后台运行

hiz5n14c  于 2023-05-01  发布在  React
关注(0)|答案(2)|浏览(151)

我正试图实现与React Native应用程序与此插件react-native-push-notifications推送通知.我成功的是得到通知时,应用程序正在运行(在前台),但我想做的是得到本地通知时,应用程序被关闭(后台),不运行,当我得到通知进入应用程序.
这是我的代码--

PushNotification.createChannel({
    channelId: "alarm-channel",
    channelName: "Alarm Channel",
    importance: 4,
    vibrate: true,
  });
};

const [selectedDate, setSelectedDate] = useState(new Date());
const handleDatePicker = (dateTime) => {
  const fireDate = dateTime;

  PushNotification.localNotificationSchedule({
    channelId: "alarm-channel",
    title: 'title',
    id: alarmNotifData.id,
    message: 'message',
    date: fireDate ,
    soundName: "Default",
    actions: ["Snooze", "Stop Reminder"],
    importance: Importance.HIGH,
    playSound: true,
    allowWhileIdle: true,
    invokeApp: false,
    priority: "high",
    timeoutAfter: 50000,
    autoCancel: false,
    vibrate: true,
    vibration: 500,
  });
};

handleDatePicker(selectedDate);
snvhrwxg

snvhrwxg1#

如果您希望在后台实现通知。我强烈建议采用@notifee/react-native包。
Installation instructions
你可以使用React Native AppState来检查你当前是在应用的前台还是后台。
对于iOS,我个人喜欢使用AppState.current === "inactive",因为它的生命周期总是活动-〉非活动-〉后台。
对于Android,我使用AppState.current === "background",因为Android只有active -〉background
首次导入AppState和notifee

import {AppState} from "react-native"
import notifee from "@notifee/react-native";

在应用程序设置代码中,为appState创建一个状态变量,并设置一个AppState侦听器

const [appState, setAppState] = useState(AppState.currentState);

  // This is used as a callback function whenever AppState changes
  const handleAppStateChange = useCallback(
    (newState: any) => {
      console.log(`AppState changed to ${newState}`);
      setAppState(newState);
    },
    []
  );

  // Initial useEffect to set things up
  useEffect(() => {
    let isActive = true;
    let appStateSubscriber: NativeEventSubscription;
    const loadNavSubscriber = async () => {
      if (isActive) {
        // Adding the listener for whether the user leaves the app
        console.log(`Adding AppState event listener`);
        appStateSubscriber = AppState.addEventListener("change", 
        handleAppStateChange);
      }
    };
    loadNavSubscriber();
    
    // It's always good practice to ask the user for notification permissions
    const getNotificationPermissions = async () => {
      if (isActive) {
        const settings = await notifee.requestPermission();
      }
    };
    getNotificationPermissions();
    return () => {
      isActive = false;
      if (appStateSubscriber) appStateSubscriber.remove();
    };
  }, []);

然后,在代码中的某个地方,你可以说。

if (appState === "active") {
  // no need to notify 
} else if (Platform.OS === "ios" && appState === "inactive") {
  // notify when background logic occurs
} else if (Platform.OS === "android" && appState === "background") {
  // notify when background logic occurs
}

在android中,如果你在打开一个通知时发现你的应用程序的一个新示例正在被创建,请确保检查你的AndroidManifest.xml。过去我花了几个小时才修好。

android:windowSoftInputMode="adjustPan"
        android:launchMode="singleTask"
        android:exported="true"

AndroidManifest.xml所讨论整个活动

<activity
      android:name=".MainActivity"
      android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
      android:windowSoftInputMode="adjustPan"
        android:launchMode="singleTask"
        android:exported="true">
     <intent-filter>
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="YOUR_APP_NAME" />
    </intent-filter>
    </activity>

祝你好运!

pkwftd7m

pkwftd7m2#

在应用关闭时使用后台服务运行代码。对于Android,react-native有Headless。js,但要做到这一点,你需要写一些原生代码。不幸的是,react-native目前没有IOS文档。
对于Android:https://reactnative.dev/docs/headless-js-android
这是一个适用于iOS和Android的库:https://www.npmjs.com/package/react-native-background-actions

相关问题