React Native Push Notifications 在 Android 中不工作,但在 iOS 中工作正常

React Native Push Notifications not working in Android but works fine on iOS

我最近在我的 React Native 应用程序中设置了推送通知,它在 iOs 中运行良好,但在 Android 中无法弹出。这是我调用来触发通知的函数。

function pushNotif(){ 
        PushNotification.localNotification({
                channelId: "specialid", // (required) channelId, if the channel doesn't exist, notification will not trigger.
                title: "hello",
                message: "test message"
        })
}

这是我在上面配置推送通知的地方

// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
   // (optional) Called when Token is generated (iOS and Android)
   onRegister: function (token) {
   console.log("TOKEN:", token);
    },

    // (required) Called when a remote is received or opened, or local notification is opened
    onNotification: function (notification) {
        console.log("NOTIFICATION:", notification);     
    // process the notification   
    // (required) Called when a remote is received or opened, or local notification is opened
        notification.finish(PushNotificationIOS.FetchResult.NoData);
            },
    // (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
    onAction: function (notification) {
        console.log("ACTION:", notification.action);
        console.log("NOTIFICATION:", notification);
            // process the action
            },
            // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
     onRegistrationError: function(err) {
           console.error(err.message, err);
            },
     // IOS ONLY (optional): default: all - Permissions to register.
            permissions: {
                alert: true,
                badge: true,
                sound: true,
            },
     // Should the initial notification be popped automatically
            // default: true
            popInitialNotification: true,
            /**
             * (optional) default: true
             * - Specified if permissions (ios) and token (android and ios) will requested or not,
             * - if not, you must call PushNotificationsHandler.requestPermissions() later
             * - if you are not using remote notification or do not have Firebase installed, use this:
             *     requestPermissions: Platform.OS === 'ios'
             */
            requestPermissions: true,
            });

正如我所说,它在 iOS 上运行良好,当我删除 channelId(我知道 android 需要它)时,我收到此消息... No Channel ID Passed. Notification may not work

这让我相信它正在以某种方式但不完全配置。

以下是我的其余配置文件:https://github.com/zo0r/react-native-push-notification

android/build.gradle

buildscript {
    ext {
        googlePlayServicesVersion = "+" // default: "+"
        firebaseMessagingVersion = "+" // default: "21.1.0"
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
        ndkVersion = "20.1.5948944"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
        classpath 'com.google.gms:google-services:4.3.10'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

android/app/src/main/AndroidManifest.xml

...
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
             <!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        <!-- Change the resource name to your App's accent color - or any other color you want -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
...

android/app/src/main/java/com/{app_name}/MainActivity.java

...
import com.facebook.react.ReactActivity;
import android.content.Intent;



public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  public void onNewIntent(Intent intent) {
      super.onNewIntent(intent);
  }
  @Override
  protected String getMainComponentName() {
    return "cjcChatApp";
  }
}

我怎样才能让它在 Android 上运行?

我想你忘了创建香奈儿,你可以试试这个:

function pushNotif(){
  PushNotification.createChannel(
    {
      channelId: "specialid", // (required)
      channelName: "Special messasge", // (required)
      channelDescription: "Notification for special message", // (optional) default: undefined.
      importance: 4, // (optional) default: 4. Int value of the Android notification importance
      vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
    },
    (created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
  );
  PushNotification.localNotification({
    channelId:'specialid', //his must be same with channelid in createchannel
    title:'hello',
    message:'test message'
  })
 }