Подтвердить что ты не робот

IncompatibleClassChangeError после обновления до Android Build Tools 25.1.6 GCM/FCM

С тех пор как я обновился до Android SDK Tools 25.1.6 и Android Support Repository 32.0.0 (сегодня утром), я получил следующую ошибку, я ничего не менял в своем коде, и он все еще работает на моем компьютере коллеги ( Android SDK Tools 25.1.1 + Android Support Repository 30.0.0).

java.lang.IncompatibleClassChangeError: The method 
     'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' 
     was expected to be of type virtual but instead was found to be of type direct 
     (declaration of 'java.lang.reflect.ArtMethod' appears in /system/framework/core-libart.jar)

     at com.google.android.gms.iid.zzd.zzeb(Unknown Source)
     at com.google.android.gms.iid.zzd.<init>(Unknown Source)
     at com.google.android.gms.iid.zzd.<init>(Unknown Source)
     at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
     at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
     at com.xxxxxxx.utils.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:55)
     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:145)
     at android.os.HandlerThread.run(HandlerThread.java:61)

Вот фрагмент кода, который сбой:

InstanceID instanceID = InstanceID.getInstance(this); // <-- crash here
String instanceIDToken = instanceID.getToken(getString(R.string.google_app_id),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

Это когда я пытаюсь получить токен из облачных сообщений Google.

Я импортирую GCM в Gradle с разделенными игровыми сервисами:

 compile 'com.google.android.gms:play-services-analytics:9.0.0' 
 compile 'com.google.android.gms:play-services-maps:9.0.0'
 compile 'com.google.android.gms:play-services-location:9.0.0' 
 compile 'com.google.android.gms:play-services-gcm:9.0.0' 
 compile 'com.google.android.gms:play-services-base:9.0.0'

ИЗМЕНИТЬ отключив GCM, исправлена ​​проблема, поэтому я предполагаю, что я должен перейти на Firebase Cloud Message

EDIT2 На моем устройстве Google Play Services 9.0 (вчера было 8.4.x). Теперь он больше не падает, но жалуется на дескриптор модуля

 Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor"
 Firebase API initialization failure.

Есть ли у кого-то подобная ошибка и как ее исправить?

Fixed Особая благодарность @stegranet. ./gradlew -q app:dependencies --configuration compile помогает определить, какие зависимости включают SDK 24.x

Основная проблема - некоторая библиотека импортирует последнюю библиотеку поддержки, используя знак + вместо версии. Это вызывает проблему, включая последнюю доступную версию.

Поэтому избегайте зависимостей sign +;)

4b9b3361

Ответ 1

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

Просто запустите gradle -q app:dependencies --configuration compile и проверьте вывод для таких записей:

+--- com.mcxiaoke.viewpagerindicator:library:2.4.1
|    \--- com.android.support:support-v4:+ -> 24.0.0-beta1 (*)

Как Диего Джорджини сказал, что эта версия слишком высока ( >= 24). Поэтому обновите зависимости в build.gradle как

compile('com.mcxiaoke.viewpagerindicator:library:2.4.1') {
    exclude module: 'support-v4';
}
compile 'com.android.support:support-v4:23.4.0'

Ответ 2

обновление может 27:

мы только что выпустили обновление (version 9.0.1), чтобы исправить несовместимость, о которой я упоминал в своем первом редактировании.
Обновите свои зависимости и сообщите нам, если это все еще проблема.

Спасибо!


оригинальный ответ Май 20:

Проблема, с которой вы столкнулись, связана с несовместимостью между play-services / firebase sdk v9.0.0 и com.android.support:appcompat-v7 >= 24
(версия, выпущенная с android-N sdk)

Вы можете исправить это, настроив таргетинг на более раннюю версию библиотеки поддержки. Как:

compile 'com.android.support:appcompat-v7:23.4.0'

Ответ 3

Я обновил зависимости play-services в build.gradle

dependencies {
    compile 'com.google.android.gms:play-services:9.0.0'
}

Чтобы исправить конфликт версии, либо обновив версию плагина google-services, я должен был обновить google-сервисы в build.gradle в корневой папке проекта

dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
}

Вы можете получить последнее обновление google-сервисов здесь.

Хотя он не избегает исключения, но его не сбивает приложение больше на моей стороне.

Обновление

Я мог бы избежать краха, обновив студию Android с бета-канала. Затем обновите свой platform/build-tools внутри SDK.

введите описание изображения здесь

Ответ 4

моя работала со следующим:

Уровень приложения gradle

dependencies {
 compile 'com.android.support:appcompat-v7:23.4.0'
 compile 'com.android.support:design:23.4.0'
 compile 'com.google.android.gms:play-services:9.0.0'
}

уровень корня gradle

dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
}

Ответ 6

Случилось мне из-за обновления facebook этого sdk, и у меня был

compile 'com.facebook.android:facebook-android-sdk:4.+'

заменив его на

compile 'com.facebook.android:facebook-android-sdk:4.15.0'

решил мою проблему.

Ссылка: https://developers.facebook.com/docs/android/change-log-4.x

Ответ 7

Включая все пакеты игровых сервисов

dependencies {
  compile 'com.google.android.gms:play-services:9.0.0'
}

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

EDIT:

Я заменил GCM на firebase, обновленную студию Android от 2.1 до 2.2, чтобы исправить проблему мгновенного запуска с помощью аналитики firebase, обновил инструменты сборки до 24-rc4 и инструменты платформы до 24-rc3 и сохранил версию моей поддержки libs до 23.4 +0,0. Теперь все работает хорошо.

Ответ 8

У меня была та же проблема и возврат из Android Support Repository 32.0.0 в Android Support Repository 31.0.0 решил.

Ответ 9

Для Android push-уведомления с GCM 2016:

1) в Android SDK- > SDK Tools проверьте службы Google Play

2) в gradle добавить в зависимости только одну строку:

compile 'com.google.android.gms:play-services-gcm:9.4.0'

(нет определенного пути к классам, и он работает для меня)

3) вы должны создать 3 класса (GCMPushReceiverService, GCMRegistrationIntentService, GCMTokenRefreshListenerService)

4.1) для GCMTokenRefreshListenerService:

package com.myapp.android;

/**
 * Created by skygirl on 02/08/2016.
 */
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;

public class GCMTokenRefreshListenerService extends InstanceIDListenerService {

    //If the token is changed registering the device again
    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, GCMRegistrationIntentService.class);
        startService(intent);
    }
}

4.2) Код для GCMRegistrationIntentService (изменение authorizedEntity с вашим номером проекта):

package com.myapp.android;

/**
 * Created by Skygirl on 02/08/2016.
 */
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

public class GCMRegistrationIntentService extends IntentService {
    //Constants for success and errors
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
    public static final String REGISTRATION_ERROR = "RegistrationError";

    //Class constructor
    public GCMRegistrationIntentService() {
        super("");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        //Registering gcm to the device
        registerGCM();
    }

    private void registerGCM() {
        //Registration complete intent initially null
        Intent registrationComplete = null;

        //Register token is also null
        //we will get the token on successfull registration
        String token = null;
        try {
            //Creating an instanceid
            InstanceID instanceID = InstanceID.getInstance(this);
            String authorizedEntity = "XXXXXXXXXX"; //  your project number

            //Getting the token from the instance id
            token = instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

            //Displaying the token in the log so that we can copy it to send push notification
            //You can also extend the app by storing the token in to your server
            Log.w("GCMRegIntentService", "token:" + token);

            //on registration complete creating intent with success
            registrationComplete = new Intent(REGISTRATION_SUCCESS);

            //Putting the token to the intent
            registrationComplete.putExtra("token", token);
        } catch (Exception e) {
            //If any error occurred
            Log.w("GCMRegIntentService", "Registration error");
            registrationComplete = new Intent(REGISTRATION_ERROR);
        }

        //Sending the broadcast that registration is completed
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
}

4.3) Код для GCMPushReceiverService:

package com.myapp.android;

/**
 * Created by Skygirl on 02/08/2016.
 */
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.google.android.gms.gcm.GcmListenerService;

//Class is extending GcmListenerService
public class GCMPushReceiverService extends GcmListenerService {

    //This method will be called on every new message received
    @Override
    public void onMessageReceived(String from, Bundle data) {
        //Getting the message from the bundle
        String message = data.getString("message");
        //Displaying a notiffication with the message
        sendNotification(message);
    }

    //This method is generating a notification and displaying the notification
    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        int requestCode = 0;
        PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.your_logo)
                .setContentTitle("Your Amazing Title")
                .setContentText(message)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent);
        noBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
    }
}

5) Не забудьте изменить имя пакета

6) В вашем mainActivity вставьте этот код:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Setup view
        setContentView(R.layout.main);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        //When the broadcast received
        //We are sending the broadcast from GCMRegistrationIntentService

        public void onReceive(Context context, Intent intent) {
            //If the broadcast has received with success
            //that means device is registered successfully
            if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)){
                //Getting the registration token from the intent
                String token = intent.getStringExtra("token");
                //Displaying the token as toast
                Toast.makeText(getApplicationContext(), "Registration token:" + token, Toast.LENGTH_LONG).show();

                //if the intent is not with success then displaying error messages
            } else if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)){
                Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show();
            }
        }
    };

    //Checking play service is available or not
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    //if play service is not available
    if(ConnectionResult.SUCCESS != resultCode) {
        //If play service is supported but not installed
        if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            //Displaying message that play service is not installed
            Toast.makeText(getApplicationContext(), "Google Play Service is not install/enabled in this device!", Toast.LENGTH_LONG).show();
            GooglePlayServicesUtil.showErrorNotification(resultCode, getApplicationContext());

            //If play service is not supported
            //Displaying an error message
        } else {
            Toast.makeText(getApplicationContext(), "This device does not support for Google Play Service!", Toast.LENGTH_LONG).show();
        }

        //If play service is available
    } else {
        //Starting intent to register device
        Intent itent = new Intent(this, GCMRegistrationIntentService.class);
        startService(itent);
    }
}

//Unregistering receiver on activity paused
@Override
public void onPause() {
    super.onPause();
    Log.w("MainActivity", "onPause");
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
}



    @Override
    public void onResume() {
 super.onResume();
        Log.w("MainActivity", "onResume");
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS));
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR));
    }

7) В вашем AndroidManifest.xml добавьте следующие строки:

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

8) в вашей консоли logcat скопируйте токен и вставьте его на сайт добавьте свой номер проекта, токен и сообщение. Это отлично работает для меня:)

Ответ 10

После полного дня, я могу подтвердить 100%, что библиотека Optimizely также каким-то образом столкнулась и вызвала эту ошибку. Чтобы быть конкретным, я использую Optimizely через Fabric. Невозможно получить Firebase для инициализации при использовании Optimizely таким образом (возможно, во всех отношениях?).

Я разместил на них свой github и напрямую свяжусь с ними...

https://github.com/optimizely/Optimizely-Android-SDK/issues/11

Ответ 11

У меня была та же проблема. Я обновил SDK-инструменты до 25.1.7 rc1, затем проблема исчезла.

Ответ 12

обновил инструменты SDK до 25.1.7 и исправил эту проблему.

Ответ 13

Ну, я только начинаю пользоваться Android. Я хотел протестировать создание пользователей в Firebase, следуя инструкциям, представленным на веб-сайте Firebase.

Я добавил эти строки в указанных местах.

classpath 'com.google.gms: google-services: 3.0.0'

compile 'com.google.firebase: firebase-auth: 9.2.0'

применить плагин: 'com.google.gms.google-services'

Но метод createUserWithEmailAndPassword продолжает показывать сбой при создании пользователей. Вот почему я посетил этот вопрос, чтобы выяснить мою проблему. Я прочитал все и применил каждый совет. но ИТ продолжал показывать неудачу. Но когда я обновляю Android Studio from 2.1.1 to 2.1.2, я мог бы создать пользователей успешно.

Но когда я проверил logcat, он сначала показал "Firebase API initialization failure", а затем показал успешную инициализацию FirebaseApp.

07-09 18:53:37.012 13352-13352/jayground.firebasetest A/FirebaseApp: Firebase API initialization failure. How can I solve

это?                                                                          java.lang.reflect.InvocationTargetException                                                                              в java.lang.reflect.Method.invokeNative(собственный метод)                                                                              в java.lang.reflect.Method.invoke(Method.java:515)                                                                              at com.google.firebase.FirebaseApp.zza(Неизвестный источник)                                                                              at com.google.firebase.FirebaseApp.initializeApp(Неизвестный источник)                                                                              at com.google.firebase.FirebaseApp.initializeApp(Неизвестный источник)                                                                              at com.google.firebase.FirebaseApp.zzeh(Неизвестный источник)                                                                              на com.google.firebase.provider.FirebaseInitProvider.onCreate(Неизвестно Источник)                                                                              в android.content.ContentProvider.attachInfo(ContentProvider.java:1591)                                                                              в android.content.ContentProvider.attachInfo(ContentProvider.java:1562)                                                                              в com.google.firebase.provider.FirebaseInitProvider.attachInfo(Неизвестно Источник)                                                                              в android.app.ActivityThread.installProvider(ActivityThread.java:5118)                                                                              в android.app.ActivityThread.installContentProviders(ActivityThread.java:4713)                                                                              в android.app.ActivityThread.handleBindApplication(ActivityThread.java:4596)                                                                              at android.app.ActivityThread.access $1600 (ActivityThread.java:169)                                                                              в android.app.ActivityThread $H.handleMessage(ActivityThread.java:1340)                                                                              на android.os.Handler.dispatchMessage(Handler.java:102)                                                                              на android.os.Looper.loop(Looper.java:146)                                                                              at android.app.ActivityThread.main(ActivityThread.java:5487)                                                                              в java.lang.reflect.Method.invokeNative(собственный метод)                                                                              в java.lang.reflect.Method.invoke(Method.java:515)                                                                              в com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:1283)                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)                                                                              в dalvik.system.NativeStart.main(собственный метод)                                                                           Причина: java.lang.NoSuchMethodError: com.google.android.gms.common.internal.zzaa.zzz                                                                              в com.google.android.gms.measurement.internal.zzx.zzbd(Неизвестно Источник)                                                                              в com.google.android.gms.measurement.AppMeasurement.getInstance(Неизвестно Источник)                                                                              в java.lang.reflect.Method.invokeNative(собственный метод)                                                                              в java.lang.reflect.Method.invoke(Method.java:515)                                                                              at com.google.firebase.FirebaseApp.zza(Неизвестный источник)                                                                              на com.google.firebase.FirebaseApp.initializeApp(Неизвестный источник)                                                                              at com.google.firebase.FirebaseApp.initializeApp(Неизвестный источник)                                                                              at com.google.firebase.FirebaseApp.zzeh(Неизвестный источник)                                                                              на com.google.firebase.provider.FirebaseInitProvider.onCreate(Неизвестно Источник)                                                                              в android.content.ContentProvider.attachInfo(ContentProvider.java:1591)                                                                              в android.content.ContentProvider.attachInfo(ContentProvider.java:1562)                                                                              в com.google.firebase.provider.FirebaseInitProvider.attachInfo(Неизвестно Источник)                                                                              в android.app.ActivityThread.installProvider(ActivityThread.java:5118)                                                                              в android.app.ActivityThread.installContentProviders(ActivityThread.java:4713)                                                                              в android.app.ActivityThread.handleBindApplication(ActivityThread.java:4596)                                                                              at android.app.ActivityThread.access $1600 (ActivityThread.java:169)                                                                              в android.app.ActivityThread $H.handleMessage(ActivityThread.java:1340)                                                                              на android.os.Handler.dispatchMessage(Handler.java:102)                                                                              на android.os.Looper.loop(Looper.java:146)                                                                              at android.app.ActivityThread.main(ActivityThread.java:5487)                                                                              в java.lang.reflect.Method.invokeNative(собственный метод)                                                                              в java.lang.reflect.Method.invoke(Method.java:515)                                                                              в com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:1283)                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)                                                                              в dalvik.system.NativeStart.main(собственный метод)     07-09 18: 53: 37.022 13352-13352/jayground.firebasetest I/FirebaseInitProvider: успешная инициализация FirebaseApp

Ответ 14

Я столкнулся с этой проблемой, и я меняю версию приложения gradle с версии 1.5.0 до 2.0.0.

изменить classpath

com.android.tools.build:gradle:1.5.0

к

classpath 'com.android.tools.build:gradle:2.0.0

Ответ 15

Решение 1:

dependencies {
 compile `com.android.support:appcompat-v7:23.4.0`
 compile `com.android.support:support-v4:23.4.0`
 compile `com.android.support:design:23.4.0`
 compile `com.google.android.gms:play-services:9.0.0`
}

Решение 2: обнаружение несовместимого в папке .idie/libraries/     Некоторое время вы объявляете игровые сервисы-объявления: 8.4.0 одновременно с play-services-gcm: 9.0.0     . вы должны переопределить обнаруженные вами несовместимые библиотеки build.grade.