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

Не удается разрешить символ "GoogleCloudMessaging" GCM

Я пытаюсь заставить GCM работать в моем приложении (чтобы уведомить пользователей, когда наши часы меняются, или когда у нас есть какие-либо промо-роли), но я продолжаю получать ошибку Cannot resolve symbol 'GoogleCloudMessaging' при попытке использовать Google Cloud API обмена сообщениями.

Я использую недавно выпущенную IDE студию Android, чтобы ее кодировать.

Вот мой код GcmBroadcastReciever.java:

import android.R;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class GcmBroadcastReceiver extends BroadcastReceiver 
{
    static final String TAG = "GCMDemo";
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    Context ctx;
    GoogleCloudMessaging gcm; // I get the error here

    @Override
    public void onReceive(Context context, Intent intent) {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); //error
        ctx = context;
        String messageType = gcm.getMessageType(intent); //cannot resolve method here
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { //error
            sendNotification("Send error: " + intent.getExtras().toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { //error
            sendNotification("Deleted messages on server: " +
                    intent.getExtras().toString());
        } else {
            sendNotification("Received: " + intent.getExtras().toString());
        }
        setResultCode(Activity.RESULT_OK);
    }

    // Put the GCM message into a notification and post it.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                new Intent(ctx, Activity.class), 0);

        Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
    }
}
4b9b3361

Ответ 1

В следующих разделах описывается процесс создания GCM реализация. Прежде чем начать, не забудьте настроить Google Play Услуги SDK. Вам нужен этот SDK для использования методов GoogleCloudMessaging. Строго говоря, единственное, что вам абсолютно необходимо API для обмена сообщениями вверх по потоку (от устройства к облаку), но он также предлагает рекомендуется оптимизировать API регистрации.

Вы настроили SDK Google Play Services?

Вы должны:

  • Установите SDK служб Google Play
  • Ссылка на проект библиотеки <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ в вашем проекте Android.

Чтобы установить SDK сервисов Google Play для разработки:

 1. Launch the SDK Manager.
     - From Eclipse (with ADT), select Window > Android SDK Manager.
     - On Windows, double-click the SDK Manager.exe file at the root of the Android
       SDK directory.
     - On Mac or Linux, open a terminal and navigate to the tools/ directory in 
       the Android SDK, then execute android sdk.
 2. Install the Google Play services SDK.
    Scroll to the bottom of the package list, expand Extras, select Google Play 
    services, and install it. 
    The Google Play services SDK is saved in your Android SDK environment at
    <android-sdk>/extras/google/google_play_services/.
 3. Install a compatible version of the Google APIs platform. 
    If you want to test your app on the emulator, expand the directory for
    Android 4.2.2 (API 17) or a higher version, select Google APIs, and
    install it. Then create a new AVD with Google APIs as the platform target. 
    Note: Only Android 4.2.2 and higher versions of the Google APIs platform
    include Google Play services.

Ответ 2

Если вы используете Android Studio:

1) Загрузил SDK Google Play (с помощью диспетчера SDK):

SDK Manager

2) Не забудьте нажать "Synch Project с кнопкой Gradle Files"

Synch Project with Gradle Files

Это помогло мне.

Ответ 3

Если вы находитесь в Android Studio, убедитесь, что в build.gradle у вас есть:

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

а затем запустите build.

Это сработало для меня.

Ответ 4

Убедитесь, что вы добавили зависимости в build.gradle > Sync > Build - Clean Project.

Работал для меня:)

Ответ 5

Попробуйте очистить свой проект. Работал для меня.