React Native Android - 本地预定推送通知适用于模拟器,但不适用于真实设备

问题描述

我正在将定时通知集成到我正在开发的应用程序中。我希望每天早上 8 点收到通知。我正在使用图书馆:zo0r/react-native-push-notification。奇怪的是,通知在我的 android studio (Nexus 6 API 25) 模拟器上运行得非常好。但是当我创建一个 apk 并将其安装在我的三星 A7 上时,通知不再起作用。我已经检查了该应用程序是否具有所需的权限,并且确实如此。我没有使用 Firebase 或任何其他库来接收通知。

AndroidManifest.xml

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<permission
   android:name="${applicationId}.permission.C2D_MESSAGE"
   android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

<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"
>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
            android:value="Notification Channel"/>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
            android:value="Channel for all app notifications"/>
<meta-data android:name="expo.modules.updates.EXPO_SDK_VERSION" android:value="29"/>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
            android:resource="@color/splashscreen_background"/>
<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>
<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.RNPushNotificationListenerServiceGcm"
         android:exported="false" >
        <intent-filter>
         <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>
<service
    android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
    android:exported="false" >
    <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:screenOrientation="portrait"
  android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
  android:launchMode="singleTask"
  android:windowSoftInputMode="adjustResize"
  android:theme="@style/Theme.App.SplashScreen"
>
  <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"/>

build.gradle

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

buildscript {
ext {
    buildToolsVersion = "29.0.2"
    minSdkVersion = 21
    compileSdkVersion = 29
    targetSdkVersion = 29
}
repositories {
    google()
    jcenter()
}
dependencies {
    classpath("com.android.tools.build:gradle:3.5.3")

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

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

    google()
    jcenter()
    maven { url 'https://www.jitpack.io' }
}
}

(app) build.gradle

apply plugin: "com.android.application"

 import com.android.build.OutputFile

 project.ext.react = [
     enableHermes: false
 ]

apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/expo-constants/scripts/get-app-config-android.gradle"
apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"

def enableSeparateBuildPerCPUArchitecture = false


def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'


def enableHermes = project.ext.react.get("enableHermes",false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    dexOptions {
       javaMaxHeapSize "3g"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

defaultConfig {
    applicationId "com.trainingapp"
    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"
    }
}
signingConfigs {
    debug {
        storeFile file('debug.keystore')
        storePassword 'android'
        keyAlias 'androiddebugkey'
        keyPassword 'android'
    }
    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
    }
}
}
buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    release {
        // Caution! In production,you need to generate your own keystore file.
        // see https://reactnative.dev/docs/signed-apk-android.
        signingConfig signingConfigs.debug
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"),"proguard-rules.pro"
        signingConfig signingConfigs.release
        minifyEnabled true
    }
}

// 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:
        // https://developer.android.com/studio/build/configure-apk-splits.html
        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 fileTree(dir: "libs",include: ["*.jar"])
// implementation 'androidx.appcompat:appcompat:1.1.0'

//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+"  // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
  exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
    exclude group:'com.facebook.flipper'
    exclude group:'com.squareup.okhttp3',module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
    exclude group:'com.facebook.flipper'
}
addUnimodulesDependencies()

if (enableHermes) {
    def hermesPath = "../../node_modules/hermes-engine/android/";
    debugImplementation files(hermesPath + "hermes-debug.aar")
    releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
    implementation jscFlavor
}
}

// 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 from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

NotificationService.js

...
configure(onNotification) {
        PushNotification.configure({
            onRegister: function(token) {
                if(token.token != undefined)
                {
                  this.token = token.token;
                }
              },onNotification: onNotification,// IOS ONLY (optional): default: all - Permissions to register.
            permissions: {
                alert: true,badge: true,sound: true
            },requestPermissions: Platform.OS === 'ios',popInitialNotification: true,});
    }
    ...
scheduleNotification(morningTime,afternoonTime,eveningTime) {
    this.cancelAll();
    if(morningTime < new Date()){
        morningTime.setDate(morningTime.getDate() + 1);
    }
    if(afternoonTime < new Date()){
        afternoonTime.setDate(afternoonTime.getDate() + 1);
    }
    if(eveningTime < new Date()){
        eveningTime.setDate(eveningTime.getDate() + 1);
    }
    PushNotification.localNotificationSchedule({
        channelId: 'Notification Channel',playSound: true,soundName: 'default',message: "Morning Notification!",date: morningTime,repeatType: "day",allowWhileIdle: true,});
    PushNotification.localNotificationSchedule({
        channelId: 'Notification Channel',message: "Afternoon notification!",date: afternoonTime,message: "Evening notification!",date: eveningTime,});
}

老实说,我不知道哪些数据是重要的/与这个问题相关的,所以如果我错过了任何数据,请给出一个标志并更新帖子。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)