Почему не создается токен устройства?

Я пытаюсь использовать реагировать родные push-уведомления, и я застрял на этом уже несколько дней, и я просто не могу найти способ заставить его работать. Я знаю, что это поднималось несколько раз за эти годы с разной степенью успеха, и я пробовал все «решения», но безуспешно.

NB... Я еще не пробовал это на iOS, так что это в основном проблема Android.

Я следовал инструкциям и искал способы устранения неполадок, но не могу получить токен устройства от onRegister.

Я могу заставить локальное уведомление срабатывать при загрузке, и onNotification вызывается при взаимодействии, но без токена.

Я не уверен, насколько это актуально, но я подумал, что мне придется дать разрешение (?), Но хотя requestPermissions правда, меня никогда не спрашивают. Я немного покопался, и в node_modules\react-native-push-notification\index.js есть две функции, запрашивающие разрешения.

Это вызывается автоматически и имеет правильный идентификатор отправителя

// Prevent requestPermissions called twice if ios result is pending
Notifications._requestPermissions

Это вызывается только в том случае, если я явно вызываю PushNotifications.requestPermissions(), но senderID не определен

// Stock requestPermissions function
Notifications.requestPermissions

Я пробовал множество различных комбинаций добавления или удаления строк из Gradle и манифеста, но ничего не сработало, поэтому я снова начал только со строк из документации. Первоначально у меня был вызов configurePushNotifications() в моей функции входа в систему, но я прочитал, что его следует вызывать из самого высокого компонента перед загрузкой JS, поэтому я переместил его в index.js, но это не имело никакого значения, по-прежнему нет токена.

Я буквально в тупике, и мне действительно не помешала бы какая-то помощь, пожалуйста, есть пасхалка Ferrero Rocher для тех, кто решит ее!

Спасибо ххх

  • Тестирование в Windows
  • Android-устройство, не эмулятор
  • реагировать родной cli: 2.0.1
  • реактивный: 0,59,5
  • реагировать-нативное-push-уведомление": ^ 3.1.3,

AndroidМанифест

<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
          package = "com.myApp">

    <uses-permission android:name = "android.permission.INTERNET" />
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->
    <uses-permission android:name = "android.permission.WAKE_LOCK" />
    <permission
            android:name = "${applicationId}.permission.C2D_MESSAGE"
            android:protectionLevel = "signature" />
    <uses-permission android:name = "${applicationId}.permission.C2D_MESSAGE" />
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->

    <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">
        <activity
                android:name = ".MainActivity"
                android:label = "@string/app_name"
                android:configChanges = "keyboard|keyboardHidden|orientation|screenSize"
                android:windowSoftInputMode = "adjustResize">
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />
                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name = "com.facebook.react.devsupport.DevSettingsActivity" />

        <meta-data  android:name = "com.dieam.reactnativepushnotification.notification_channel_name"
                    android:value = "YOUR NOTIFICATION CHANNEL NAME"/>
        <meta-data  android:name = "com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value = "YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
        <!-- 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 = "@android:color/white"/>

        <!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <receiver
                android:name = "com.google.android.gms.gcm.GcmReceiver"
                android:exported = "true"
                android:permission = "com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name = "com.google.android.c2dm.intent.RECEIVE" />
                <category android:name = "${applicationId}" />
            </intent-filter>
        </receiver>
        <!-- < Only if you're using GCM or localNotificationSchedule() > -->

        <!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <service
                android:name = "com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm"
                android:exported = "false" >
            <intent-filter>
                <action android:name = "com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <!-- </ Only if you're using GCM or localNotificationSchedule() > -->

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

</manifest>

приложение\сборка.градле

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.sumoshift"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation ("com.google.android.gms:play-services-gcm:12.0.1") {
        force = true
    }
    implementation ("com.google.firebase:firebase-messaging:12.0.1") {
        force = true
    }
    implementation project(':react-native-push-notification')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-vector-icons')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'

android\build.gradle

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

уведомления.js

configurePushNotifications(shouldRegisterDeviceDetails) {
        console.info('notifications Notification configurePushNotifications');

        Notification.create({message: 'Test message working'});

        PushNotification.configure({

            // (optional) called when Token is generated (Android & iOS)
            onRegister:  function (registrationToken) {
                console.info('notifications Notification configurePushNotifications onRegister registrationToken: ', registrationToken);

                if (shouldRegisterDeviceDetails) {
                    console.info('registering device');

                    API.editShifterData(8, {
                        device_token: registrationToken.token,
                        phone_type: registrationToken.os
                    })
                        .then((response) => {
                            console.info('notifications Notification configurePushNotifications onRegister response: ', response);
                        })
                        .catch((error) => {
                            console.info('notifications Notification configurePushNotifications onRegister error: ', error);
                        })
                }
            },


            // (required) Called when a remote or local notification is opened or received
            onNotification: function (notification) {
                console.info('notifications Notification configurePushNotifications onNotification notification: ', notification);

                if (notification.userInteraction) {
                    console.info('notifications Notification configurePushNotifications onNotification userInteraction TRUE');

                    Notification.open(notification);
                } else {
                    console.info('notifications Notification configurePushNotifications onNotification userInteraction FALSE');

                    Notification.create(notification);
                }
            },

            // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
            senderID: "xxxxxxxxxxx",

            // 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
             */
            requestPermissions: true,
        });
    }

Еще раз спасибо ххх

Умерло ли Create-React-App?
Умерло ли Create-React-App?
В этом документальном фильме React.dev мы исследуем, мертв ли Create React App (CRA) и какое будущее ждет этот популярный фреймворк React.
Освоение React Native: Пошаговое руководство для начинающих
Освоение React Native: Пошаговое руководство для начинающих
React Native - это популярный фреймворк с открытым исходным кодом, используемый для разработки мобильных приложений. Он был разработан компанией...
В чем разница между react native и react ?
В чем разница между react native и react ?
React и React Native - два популярных фреймворка для создания пользовательских интерфейсов, но они предназначены для разных платформ. React - это...
От React к React Native: Руководство для начинающих по разработке мобильных приложений с использованием React
От React к React Native: Руководство для начинающих по разработке мобильных приложений с использованием React
Если вы уже умеете работать с React, создание мобильных приложений для iOS и Android - это новое приключение, в котором вы сможете применить свои...
Хуки React: что это такое и как их использовать
Хуки React: что это такое и как их использовать
Хуки React - это мощная функция библиотеки React, которая позволяет разработчикам использовать состояние и другие возможности React без написания...
3
0
1 657
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Если кто-то столкнется с той же проблемой, мне пришлось добавить в манифест несколько дополнительных строк, которые не были упомянуты в документации пакета.

<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"/>
    </intent-filter>
</receiver>
<service android:name = "com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

Но я буду абсолютно честен, глядя на раздел проблем пакета на NPM, кажется, что там так много всего, что не было упомянуто, и есть много разных решений от разных людей, так что пока это то, что я использовал чтобы заставить его работать, это немного бесплатно для всех.

Удачи!

@VishalGoel - Привет! Если вы используете Xcode, не забудьте включить push-уведомления на вкладке «Возможности».

Richard KeMiKaL GeNeRaL Denton 10.10.2019 14:52

На самом деле я тестирую на симуляторе. Токен был сгенерирован на реальном устройстве.

Vishal Goel 10.10.2019 15:14

Другие вопросы по теме