Как исправить ": response-native-firebase: compileDebugJavaWithJavac FAILED" + не удается найти import com.google.firebase.iid.FirebaseInstanceIdService; - PullRequest
1 голос
/ 09 июня 2019

Недавно я клонировал новый проект и попытался react-native run-android К сожалению, по некоторым причинам я не могу запустить свой проект, и терминал показывает мне эту ошибку: > Task :react-native-firebase:compileDebugJavaWithJavac FAILED, и выше этой ошибки я увидел больше информации об этом подробно => 'не могу найти символ импорта com.google.firebase. iid.FirebaseInstanceIdService;»

.

Я много искал эту проблему и обнаружил, что «FirebaseInstanceIdService» устарел, поэтому я должен прокомментировать import com.google.firebase.iid.FirebaseInstanceIdService; в InstanceIdService.java, расположенном в => \node_modules\react-native-fcm\android\src\main\java\com\evollu\react\fcm\InstanceIdService.java, кроме того, я должен также внести некоторые другие изменения. но я снова получаю ту же ошибку.

Содержимое InstanceIdService.java (до внесения каких-либо изменений):

package com.evollu.react.fcm;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class InstanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "InstanceIdService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. This call is initiated by the
     * InstanceID provider.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // Broadcast refreshed token
        Intent i = new Intent("com.evollu.react.fcm.FCMRefreshToken");
        Bundle bundle = new Bundle();
        bundle.putString("token", refreshedToken);
        i.putExtras(bundle);

        final Intent message = i;

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            public void run() {
                // Construct and load our normal React JS code bundle
                ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
                ReactContext context = mReactInstanceManager.getCurrentReactContext();
                // If it's constructed, send a notification
                if (context != null) {
                    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(message);
                } else {
                    // Otherwise wait for construction, then send the notification
                    mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
                        public void onReactContextInitialized(ReactContext context) {
                            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(message);
                        }
                    });
                    if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
                        // Construct it in the background
                        mReactInstanceManager.createReactContextInBackground();
                    }
                }
            }
        });
    }
}

Содержание отредактированного InstanceIdService.java:

package com.evollu.react.fcm;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.google.firebase.iid.FirebaseInstanceId;
//import com.google.firebase.iid.FirebaseInstanceIdService; //Commented FirebaseInstanceIdService
import com.google.firebase.messaging.FirebaseMessagingService;  //ADD FirebaseMessagingService

// public class InstanceIdService extends FirebaseMessagingService {
public class MyFireBaseInstanceIDService  extends FirebaseMessagingService {

    private static final String TAG = "InstanceIdService";
    // private static final String TAG = MyFireBaseInstanceIDService.class.getSimpleName();;

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. This call is initiated by the
     * InstanceID provider.
     */
    // [START refresh_token]
    @Override
    public void onNewToken(String token) { //Added onNewToken method
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // Broadcast refreshed token
        Intent i = new Intent("com.evollu.react.fcm.FCMRefreshToken");
        Bundle bundle = new Bundle();
        bundle.putString("token", refreshedToken);
        i.putExtras(bundle);

        final Intent message = i;

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            public void run() {
                // Construct and load our normal React JS code bundle
                ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
                ReactContext context = mReactInstanceManager.getCurrentReactContext();
                // If it's constructed, send a notification
                if (context != null) {
                    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(message);
                } else {
                    // Otherwise wait for construction, then send the notification
                    mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
                        public void onReactContextInitialized(ReactContext context) {
                            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(message);
                        }
                    });
                    if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
                        // Construct it in the background
                        mReactInstanceManager.createReactContextInBackground();
                    }
                }
            }
        });
    }
}

Обратите внимание, что: У меня одна и та же проблема как в react-native-fcm, так и в react-native-firebase, похоже, мне нужно внести некоторые изменения в 'RNFirebaseInstanceIdService.java' и 'RNFirebasePerformance.java'

ПРОСТО ДОБАВИЛ ЭТОТ ЗАПИСЬ ПОСЛЕ ТОГО, КАК Я РЕШЕН СЕБЕ ПРОБЛЕМА :: это вообще не про реактив-native-fcm! это было все о реактивном-собственном-firebase, как я уже говорил, хотя устаревший 'instanceIdService' существует в реактивном-родном-fcm, который когда-то я пытался внести некоторые изменения.

Спасибо

Ответы [ 2 ]

0 голосов
/ 10 июня 2019

Таким образом, каждый раз, когда я сталкивался с ошибкой: > Task :react-native-firebase:compileDebugJavaWithJavac FAILED будут некоторые проблемы с устаревшим FirebaseInstanceIdService в RNFirebaseInstanceIdService.java файле, а также incrementCounter, расположенным в RNFirebasePerformance.java. Так как FirebaseInstanceIdService не рекомендуется, я прокомментировалэто и импортировало FirebaseMessagingService вместо.

(1) изменения, которые я сделал в RNFirebaseInstanceIdService.java:

package io.invertase.firebase.messaging;


import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

// import com.google.firebase.iid.FirebaseInstanceIdService;  //I commented this once because it's deprecated
import com.google.firebase.messaging.FirebaseMessagingService;  //I added this one

public class RNFirebaseInstanceIdService extends FirebaseMessagingService {
  private static final String TAG = "RNFInstanceIdService";
  public static final String TOKEN_REFRESH_EVENT = "messaging-token-refresh";

  // I commented the below codes
  // @Override  
  // public void onTokenRefresh() {
  //   Log.d(TAG, "onTokenRefresh event received");

  //   // Build an Intent to pass the token to the RN Application
  //   Intent tokenRefreshEvent = new Intent(TOKEN_REFRESH_EVENT);

  //   // Broadcast it so it is only available to the RN Application
  //   LocalBroadcastManager.getInstance(this).sendBroadcast(tokenRefreshEvent);
  // }
}

(2) изменения, которые я сделал в RNFirebasePerformance.java

...
.
.
  //somewhere in the file I searched for incrementCounter and commented it

  @ReactMethod
  public void incrementCounter(String identifier, String event) {
    // getOrCreateTrace(identifier).incrementCounter(event);  //I commented this line
  }

.
.
...

Итак, я внес эти изменения выше, и после этого это сработало для меня ... как очарование !!

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

B -) : пожалуйста, не стесняйтесь задавать мне любые вопросы, если это не работает для вас

0 голосов
/ 10 июня 2019

В проекте, который вы использовали, используется модуль response-native-fcm npm.Класс FirebaseInstanceIdService является устаревшим классом и был удален. Чтобы сгенерировать токен для fcm, вы можете использовать функцию onNewToken в классе MessagingInstance.java и удалить любую ссылку на класс FirebaseInstanceIdService в проекте.Код метода onNewToken: -

@Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.d("NEW_TOKEN", s);
    }

Пожалуйста, следуйте инструкциям по ссылке ниже, чтобы преодолеть ваши ошибки: -

FirebaseInstanceIdService устарела .

Редактировать: - если вы не используете push-уведомления в проекте, вы можете удалить весь модульact-native-fcm из проекта.

...