简体   繁体   中英

I got message id from gcm. but I'm not receiving on emulator

this is the sender code which is used to send message to gcm.

        //sJSONObject obj = new JSONObject();
        Sender sender = new Sender(GOOGLE_SERVER_KEY);
        Message message = new Message.Builder().timeToLive(120)
                .delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
        System.out.println("regId: " + regId);
        Object result = sender.send(message, regId, 5);

        if (StringUtils.isEmpty(((Result) result).getErrorCodeName())) {
            System.out.println("success");
            System.out.println(result.toString());
        }
        else{
            System.out.println(((Result) result).getErrorCodeName());
            System.out.println(result.toString());
        }

Manifest file:

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

<permission
    android:name="com.javapapers.android.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.javapapers.android.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    <activity
        android:name=".RegisterActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="com.javapapers.android.MainActivity"
        android:configChanges="orientation|keyboardHidden"
        android:label="@string/app_name" >
    </activity>

    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.javapapers.android" />
        </intent-filter>
    </receiver>

    <service android:name=".GCMNotificationIntentService" />

    <!-- added by shashank -->
    <meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
</application>

CCMBroadcastreciever:

package com.javapapers.android;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Log.d("GCMBroadcastReceiver", "OnReceive method");
    System.out.println( "Broadcast receiver OnReceive method");
    ComponentName comp = new ComponentName(context.getPackageName(),
            GCMNotificationIntentService.class.getName());
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}
}

GCMNotificationIntentService:

package com.javapapers.android;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

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

public class GCMNotificationIntentService extends IntentService {

public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;

public GCMNotificationIntentService() {
    super("GcmIntentService");
}

public static final String TAG = "GCMNotificationIntentService";

@Override
protected void onHandleIntent(Intent intent) {
    Log.d("GCMNotificationIntentService", "OnHandleIntent method");
    System.out.println( "GCMNotificationIntentService OnHandleIntent method");
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                .equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                .equals(messageType)) {
            sendNotification("Deleted messages on server: "
                    + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                .equals(messageType)) {

            for (int i = 0; i < 3; i++) {
                Log.i(TAG,
                        "Working... " + (i + 1) + "/5 @ "
                                + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }

            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

            sendNotification("Message Received from Google GCM Server: "
                    + extras.get(Config.MESSAGE_KEY));
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.gcm_cloud)
            .setContentTitle("GCM Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}
}

Output: success [ messageId=0:1414564158966354%31e4cc17f9fd7ecd ]

Still i'm not getting push notification on emulator. i have tried it on device as well. same problem occurs there as well.

I had a similar problem. I solved it using the classes in This GitHub example specifically noting the following:

Three 'services' and one 'receiver' together with all the permissions added in the github example.

AndroidManifest.xml

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />

<permission
    android:name="<yourpackagename>.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

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

<service
    android:name=".utility.MyGcmRegistrationIntentService"
    android:exported="false" >
</service>

<service
    android:name=".utility.MyGcmListenerService"
    android:exported="false" >
    <intent-filter>
        actionandroid:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter</service>

<service
    android:name=".utility.MyInstanceIdListenerService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.android.gms.iid.InstanceID"/>
    </intent-filter>
</service>

<receiver
    android:name="com.google.android.gms.gcm.GcmReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
        <category android:name="<com.example.yourpackagename>" />
    </intent-filter>
</receiver>

The Receiver is implemented in the

ActivityMain.java:

mRegistrationBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        boolean sentToken = sharedPreferences.getBoolean(SENT_TOKEN_TO_SERVER, false);
        if (sentToken) {

        } else {

        }
    }
};

@Override
protected void onResume() {
    super.onResume();

LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter("registrationComplete"));
}

@Override
protected void onPause() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
    super.onPause();
}

You can basically use the other files just like they are:

MyGcmListenerService.java - The one where you can customize your notification icon and text.

MyInstanceIDListenerService.java

QuickstartPreferences.java

RegistrationIntentService.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM