未收到GCM消息

时间:2016-04-18 09:31:06

标签: android notifications push-notification google-cloud-messaging

我一直试图实施GCM很长一段时间......但是我被卡住了...我已经在下面发布了代码和必要的细节。这是清单

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="mypackage.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

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

    <application
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@mipmap/ic_launch"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".screens.WebActivity"
            android:screenOrientation="portrait">
            <intent-filter>

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

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

        <service
            android:name=".service.GcmMessageHandler"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </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" />
                <category android:name="mypackage" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

其他相关课程文件

GcmMessageHandler:

extends GcmListenerService { 
String message;
public static final int MESSAGE_NOTIFICATION_ID = 435345;

@Override
public void onMessageReceived(String from, Bundle data) {
    message = data.getString("message");

    createNotification(from, message);
}

private void createNotification(String from, String message) {

    Context context = getBaseContext();
    NotificationCompat.Builder mbuilder = new NotificationCompat
            .Builder(context).setSmallIcon(R.mipmap.ic_launch)
            .setContentTitle(from)
            .setContentText(message);

    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mbuilder.build());
}

MyInstanceIDListenerService

extends InstanceIDListenerService {

    @Override
    public void onTokenRefresh() {

        Intent tokenrefreshIntent = new Intent(this,RegistrationIntentService.class);
        startService(tokenrefreshIntent);
    }
}

RegistrationIntentService:

extends IntentService {

    private static final String PREFS_TOKEN_KEY = "my_token_key";
    private static final String QuickstartPreferences = "QuickstartPreferences";
    private static String User_EmailId;

    String senderId;
    String token;

    SharedPreferences sharedPrefs;
    NetworkOperations networkOperations;

    public RegistrationIntentService(String name) {
        super(name);
    }

    public RegistrationIntentService() {
        super(PREFS_TOKEN_KEY);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        //        initializeClasses();
        // make call to the instance api//
        InstanceID instanceID = InstanceID.getInstance(this);
        senderId = getResources().getString(R.string.google_app_id);

        //request token that will be used by the server to send the notification//
        try {
            token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

            User_EmailId = getEmiailID(getApplicationContext());
            Log.d("register_Token: ", token);

            sendRegistrationToServer(token, User_EmailId);

        } catch (IOException e) {
            Log.d("error_httpproblem", e.getMessage() + " & " +     e.getLocalizedMessage());
            e.printStackTrace();
            sharedPrefs.edit().putBoolean(QuickstartPreferences, false).apply();
        }
    }

    private void sendRegistrationToServer(String token,String email) {

        GcmTokenPost gcmTokenPost = new GcmTokenPost();
        try {
            gcmTokenPost.postToken(token,email);
        } catch (IOException e) {
            Log.d("error_httpproblem", e.getMessage() + " & " + e.getLocalizedMessage());
            e.printStackTrace();
        }

        sharedPrefs.edit().putString(PREFS_TOKEN_KEY, token);
        sharedPrefs.edit().putBoolean(QuickstartPreferences, true).apply();

        Log.d("shared_prefs", sharedPrefs.getString(PREFS_TOKEN_KEY, "default value"));
    }

    private String getEmiailID(Context context) {
        AccountManager my_accountManager = AccountManager.get(context);
        Account account = getAccount(my_accountManager);
        if (account == null) {
            return null;
        } else {
            return account.name;
        }
    }

    private static Account getAccount(AccountManager accountManager) {
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
            account = accounts[0];
        } else {
            account = null;
        }
        return account;
    }

    //    private void initializeClasses() {
    //
    //        networkOperations = new NetworkOperations();
    //    }
}

我从gcm获得的回复

the response I get

我可以成功地将令牌从app发送到我的服务器,然后从那里发送到GCM服务器..但我无法从gcm服务器获取任何内容。

1 个答案:

答案 0 :(得分:0)

首先,我认为您应该从google开发网站https://developers.google.com/cloud-messaging/android/start尝试此教程,在您成功理解所有代码后,您可以使用此链接Add Cloud Messaging to your app

我认为您的问题出在您的RegistrationIntentService课程上,没有订阅令牌功能:

此代码由google-sample github提供

private static final String[] TOPICS = {"global"};

/**
 * Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
 *
 * @param token GCM token
 * @throws IOException if unable to reach the GCM PubSub service
 */
// [START subscribe_topics]
private void subscribeTopics(String token, String id) throws IOException {
    GcmPubSub pubSub = GcmPubSub.getInstance(this);
    for (String topic : TOPICS) {
        pubSub.subscribe(token, "/topics/" + topic, null);
    }
}
// [END subscribe_topics]