zo0r / react-native-push-notification

React Native Local and Remote Notifications
MIT License
6.75k stars 2.05k forks source link

[Android] onRegister not called, no permissions requested #910

Closed hankedori closed 3 years ago

hankedori commented 5 years ago

Hey guys, I've been trying to get this working for quite a while now, but the onRegister callback never seems to get called, no matter what configuration I try.

I'm using FCM with the following settings:

top-level build.gradle

buildscript {
    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
        googlePlayServicesVersion = "15.0.1"
        androidMapsUtilsVersion = "0.5+"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath 'com.google.gms:google-services:4.0.2'
    }
}

allprojects {
    repositories {
        google()
        mavenLocal()
        jcenter()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

AndroidManifest

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

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

    <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" />

...

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

and my PushNotification config

PushNotification.configure({
    onError: function(e) {
      console.log(e)
    },
    onRegister: function(token) {
      token.os = Platform.OS === 'ios' ? 'ios' : 'android'
      api.registerDevice(token)
    },

    onNotification: function(notification) {
     // console.log(notification)

     if (Platform.OS === 'ios') notification.finish(PushNotificationIOS.FetchResult.NoData)
    },

    senderId: SENDER_ID,
    permissions: {
     alert: true,
     badge: true,
     sound: true
    },

    popInitialNotification: true,
    requestPermissions: true
  })

Everything works well on iOS, and local notifications are working for android.

The problem I am facing is that onRegister never gets called on android (on device and on emulator) which means that there is no way for me to send remote push notifications.

I am hoping someone can help me solve this issue, or at the very least point me towards methods for debugging why it may not be called.

Thanks!

KeithM23 commented 5 years ago

Hopefully you've solved this already but if not I spotted you have

senderId: SENDER_ID,

instead of

senderID: SENDER_ID,

and also make sure SENDER_ID is the fcm id but inside a string, i.e SENDER_ID = "1234567"

martingalovic commented 5 years ago

same

senderID: "79663XXXXXXX",

and onRegister() doesn't get triggered, nor the alert with permissions request is shown.

Running on genymotion (with OpenGAPPS)

KeithM23 commented 5 years ago

@martingalovic Do you have

requestPermissions: true

if not you have to manually request the permission

martingalovic commented 5 years ago

@martingalovic Do you have

requestPermissions: true

if not you have to manually request the permission

@KeithM23 Docs say it's default value, but i have tried it, and still, nothing happening.

KeithM23 commented 5 years ago

@martingalovic When you say you don't see the alert request is this on iOS yes? On the devices we have here android never shows an alert but we always get the FCM token.

I'd also check that you've removed all the GCM code from your manifest file as this probably causes issues if left in.

martingalovic commented 5 years ago

@KeithM23 no, im talking bout android (i'm using genymotion)

Also this is my AndroidManifest.xml

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

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      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" />
    </application>

    <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" />

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
</manifest>
KeithM23 commented 5 years ago

@martingalovic it looks to me like you're missing the receiver and services i.e

`

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

I'd advise going over the setup steps again to make sure you haven't missed anything. Also make sure you've added the google services json file as well to the project.

martingalovic commented 5 years ago

@KeithM23 I added the google-services.json into android/ directory, app has been verified (the google firebase check was successfull), but no alert w/ token was displayed

Technician.js (the main file)

// ...
import UserStorage from './storage/UserStorage'

import PushNotification from 'react-native-push-notification';

PushNotification.configure({

    onRegister: (token) => {
        Alert.alert( 'FCM TOKEN:', JSON.stringify(token) );
    },

    onNotification: (notification) => {
        console.log( 'NOTIFICATION:', notification );
    },

    senderID: "7966XXXXXXXX",

    requestPermissions: true,
});

class AuthLoadingScreen extends Component {
// ...
KeithM23 commented 5 years ago

@martingalovic Did you add the receiver / services to your manifest?

martingalovic commented 5 years ago

[Solved my problem with crash]

Fix was basically to set com.google.android.gms:play-services-gcm and com.google.firebase:firebase-messaging to same version

so my app/build.gradle looks like:

dependencies {
   // ...
   compile ("com.google.android.gms:play-services-gcm:12.0.1") {
        force = true
    }
    compile ("com.google.firebase:firebase-messaging:12.0.1") {
        force = true
    }
}

https://github.com/rebeccahughes/react-native-device-info/issues/463#issuecomment-413313038

KeithM23 commented 5 years ago

@martingalovic So the app starts but you still don't get token?

Can you check Android Studio Logcat for any errors?

martingalovic commented 5 years ago

@KeithM23 no it works just fine with steps i described, thanks for help.

muhammadhaseebsohail commented 5 years ago

anyone resolve this error? i am also getting this error, and stuck here for the last 2 days, any help will be appreciated , Please anyone? i am also not getting neither the device token nor the app push notification request permission,
My AndroidManifest.xml File:

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

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
    android:name="com.waves.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.waves.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: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" />

    <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="com.waves"/>
        </intent-filter>
    </receiver>
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->

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

            <!-- <Else> -->
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <!-- </Else> -->
        </intent-filter>
    </service>

    <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"/>

</application>

gino8080 commented 5 years ago

@martingalovic saved my day!!

arapocket commented 5 years ago

So I followed what @martingalovic said. I'm using the same version number everywhere, but it still doesn't work.

thaoth58 commented 5 years ago

Sorry. I have same issue, do you guys know how to fix it?

ifalldev commented 5 years ago

@martingalovic could you share with us your build.gradle dependencies please?

martingalovic commented 5 years ago

@ifalldev

This is my build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath 'de.undercouch:gradle-download-task:3.4.3'
        classpath 'com.google.gms:google-services:4.2.0'

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

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

// subprojects {
//     afterEvaluate { 
//         project -> if (project.hasProperty("android")) { android { compileSdkVersion 26 } } 
//     }
// }

ext {
    compileSdkVersion = 26
    targetSdkVersion = 26
    buildToolsVersion = "26.0.2"
    supportLibVersion = "27.1.0"
    googlePlayServicesVersion = "12.0.1"
    firebaseVersion = "+"
    gradle3EXPERIMENTAL = "yes"
    minSdkVersion = 16
    androidMapsUtilsVersion = "0.5+"
}

And android/app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

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

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

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        applicationId "com.technician"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // 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]
            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 {
    compile project(':react-native-mauron85-background-geolocation')
    compile project(':react-native-push-notification')
    compile project(':react-native-launch-navigator')
    compile project(':react-native-camera')
    // compile project(':react-native-maps')
    compile project(':react-native-vector-icons')
    // compile project(":rncamerakit")
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    compile "com.facebook.react:react-native:+"  // From node_modules
    // implementation(project(':react-native-maps')) {
    //     exclude group: 'com.google.android.gms', module: 'play-services-base'
    //     exclude group: 'com.google.android.gms', module: 'play-services-maps'
    // }
    // implementation 'com.google.android.gms:play-services-base:10.0.1'
    // implementation 'com.google.android.gms:play-services-maps:10.0.1'

    // compile project(':react-native-geocoder')
    compile 'com.android.support:appcompat-v7:26.0.2'

    compile (project(':react-native-camera')) {
        exclude group: "com.google.android.gms"
        compile 'com.android.support:exifinterface:27.+'
        compile 'com.android.support:support-v4:27.+'
        compile ('com.google.android.gms:play-services-vision:12.0.1') {
            force = true
        }
    }

    compile ("com.google.android.gms:play-services-gcm:12.0.1") {
        force = true
    }
    compile ("com.google.firebase:firebase-messaging:12.0.1") {
        force = true
    }
}

// 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'
ifalldev commented 5 years ago

My app runs normally but it don't call onRegister method in android version (iOS is fine) ;(

LucienChu commented 5 years ago

Any one has solved this issue? Running on RN0.59.10, on Android. Local notification fires and receipted normally but device token was net fetched. Running on PHYSICAL device already.

haiflive commented 4 years ago

on my android device problem was solved to install Google Play Services

also no any error in onError: function(e) {

github-actions[bot] commented 3 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 30 days if no further activity occurs. Thank you for your contributions.

hypnoboutique commented 2 years ago

As @haiflive says, Google Play Services must be installed on the device.

My issue was that I'm developing for a feature phone (dumb phone) with no Play Services installed. 🤦