1

this is my class

public class GcmIntentService extends IntentService {

private static final String TAG = GcmIntentService.class.getSimpleName();

public GcmIntentService() {
    super(TAG);
}

public static final String KEY = "key";
public static final String TOPIC = "topic";
public static final String SUBSCRIBE = "subscribe";
public static final String UNSUBSCRIBE = "unsubscribe";


@Override
protected void onHandleIntent(Intent intent) {
    String key = intent.getStringExtra(KEY);
    switch (key) {
        case SUBSCRIBE:
            // subscribe to a topic
            String topic = intent.getStringExtra(TOPIC);
            subscribeToTopic(topic);
            break;
        case UNSUBSCRIBE:
            String topic1 = intent.getStringExtra(TOPIC);
            unsubscribeFromTopic(topic1);
            break;
        default:
            // if key is not specified, register with GCM
            registerGCM();
    }

}

/**
 * Registering with GCM and obtaining the gcm registration id
 */
private void registerGCM() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String token = null;

    try {
        InstanceID instanceID = InstanceID.getInstance(this);
        token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

        Log.e(TAG, "GCM Registration Token: " + token);

        // sending the registration id to our server
        sendRegistrationToServer(token);

        sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, true).apply();
    } catch (Exception e) {
        Log.e(TAG, "Failed to complete token refresh", e);

        sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
    registrationComplete.putExtra("token", token);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

private void sendRegistrationToServer(final String token) {
    // Send the registration token to our server
    // to keep it in MySQL

}

/**
 * Subscribe to a topic
 */
public void subscribeToTopic(String topic) {
    GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
    InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
    String token = null;
    try {
        token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        if (token != null) {
            pubSub.subscribe(token, "/topics/" + topic, null);
            Log.e(TAG, "Subscribed to topic: " + topic);
        } else {
            Log.e(TAG, "error: gcm registration id is null");
        }
    } catch (IOException e) {
        Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage());
        Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

public void unsubscribeFromTopic(String topic) {
    GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
    InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
    String token = null;
    try {
        token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        if (token != null) {
            pubSub.unsubscribe(token, "");
            Log.e(TAG, "Unsubscribed from topic: " + topic);
        } else {
            Log.e(TAG, "error: gcm registration id is null");
        }
    } catch (IOException e) {
        Log.e(TAG, "Topic unsubscribe error. Topic: " + topic + ", error: " + e.getMessage());
        Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

this is my build gradle

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

android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
    applicationId "com.ciangproduction.cp.gcmsample"
    minSdkVersion 21
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile "com.google.android.gms:play-services-gcm:8.3.0"
}

this is my error code

FATAL EXCEPTION: IntentService[GcmIntentService]
Process: com.ciangproduction.cp.gcmsample, PID: 14747
java.lang.IllegalAccessError: Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.android.gms.iid.zzd' (declaration of 'com.google.android.gms.iid.zzd' appears in /data/app/com.ciangproduction.cp.gcmsample-1/split_lib_dependencies_apk.apk:classes4.dex)
at com.google.android.gms.iid.zzd.zzdL(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.ciangproduction.cp.gcmsample.gcm.GcmIntentService.registerGCM(GcmIntentService.java:65)
at com.ciangproduction.cp.gcmsample.gcm.GcmIntentService.onHandleIntent(GcmIntentService.java:52)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)

the error code is directing to this line

InstanceID instanceID = InstanceID.getInstance(this);
        token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

Please help. I didn't get any result on the internet. I have been searching for 2 weeks and there is no result. Thank you.

  • You do realize that Java and JavaScript are completely unrelated, right? – EJoshuaS - Stand with Ukraine Jun 03 '17 at 18:30
  • Any reason you're not using [FCM](https://firebase.google.com/docs/cloud-messaging/) instead? – AL. Jun 04 '17 at 01:53
  • @jonathanrz I get this code from this article http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-2/ . I have followed the steps well. I have tried to rewrite the code 5 times and the result remains the same. By the way I'm new in android. – Kevin Ciang Jun 04 '17 at 04:34

0 Answers0