Мое приложение React Native закрывается, когда я отправляю push-уведомление через Firebase Cloud Messaging

Недавно я начал с React Native, и оказалось, что мне пришлось использовать Push-уведомления, чтобы уведомлять всех пользователей, когда запускается определенное действие, Итак, хорошо, я прочитал документы Firebase, настроил проект, установил зависимости и думаю, что все сделал нормально, но мое приложение закрывается, когда я пытаюсь отправить какое-либо уведомление в приложение, и это сводит меня с ума, потому что Я еще не видел других сообщений с этой проблемой, и я просто не знаю, как это исправить, мой крайний срок приближается, я собираюсь предоставить вам все файлы конфигурации для вас, ребята, и фактический код, обрабатывающий уведомление, хотя он по-прежнему выполняет только console.warn () в сообщении.

Файл app / build.gradle:

android {
    compileSdkVersion 27

    defaultConfig {
        applicationId "com.watcher"
        minSdkVersion 23
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    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"
        }
    }
    // 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 {
    implementation project(':react-native-vector-icons')
    implementation project(':react-native-firebase')
    implementation project(':react-native-fcm')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:27.0.+"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation("com.google.firebase:firebase-messaging:17.0.0") {
        force = true
    }
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

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

Файл build.gradle:

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

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'com.google.gms:google-services:3.2.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

MainApplication.java:

package com.watcher;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.oblador.vectoricons.VectorIconsPackage;
import io.invertase.firebase.RNFirebasePackage;
import com.evollu.react.fcm.FIRMessagingPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // <-- Add this line

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new VectorIconsPackage(),
          new RNFirebasePackage(),
          new FIRMessagingPackage(),
          new RNFirebaseMessagingPackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

AndroidManifest.xml:

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

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

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

      <service
          android:name = ".MyFirebaseInstanceIDService">
          <intent-filter>
              <action android:name = "com.google.firebase.INSTANCE_ID_EVENT"/>
          </intent-filter>
      </service>

    </application>

</manifest>

И фактический код, обрабатывающий уведомления:

async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
        this.receiveToken();
    } else {
        this.requestPermission();
    }
  }

async receiveToken() {
      let fcmToken = await AsyncStorage.getItem('fcmToken');
      if (!fcmToken) {
          fcmToken = await firebase.messaging().getToken();
          if (fcmToken) {
              await AsyncStorage.setItem('fcmToken', fcmToken);
          }
      }

      return this.messageListener = firebase.messaging().onMessage(notif => {
        try {
          console.warn(JSON.stringify(notif));
        } catch(e) {
          console.warn("error trying to handle the message")
        }
      })
    }

    async requestPermission() {
      try {
          await firebase.messaging().requestPermission();
          this.receiveToken();
      } catch (error) {
          console.warn('permission rejected');
      }
    }

componentDidMount() {
    this.makeRemoteRequest();
    this.checkPermission();
  }

  componentWillUnmount() {
    this.messageListener();
  }

У меня просто были проблемы с неправильной конфигурацией, поэтому я запустил совершенно новое приложение и настроил firebase с нуля, и оно выполнило свою работу.

Tio Zed 26.09.2018 19:57
Интеграция Angular - Firebase Analytics
Интеграция Angular - Firebase Analytics
Узнайте, как настроить Firebase Analytics и отслеживать поведение пользователей в вашем приложении Angular.
1
1
211
0

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