Google Cloud Messaging服务和听众从未在Android中调用过

时间:2016-02-04 21:21:51

标签: android android-studio google-cloud-messaging

我正在尝试在Android Studio中配置GCM以在我的应用中接收推送通知。但我的gcm服务和听众永远不会被召唤。

以下是代码:

的manifest.xml:

.nav-mobile {
    display:block;

}
.nav {
    width:100%;
    padding:0px 0 0 0;
    position:absolute;
    z-index:999999;
    top:53px;

}
.nav-list {
    display:none;
}
.nav-item {
    width:100%;
    float:none;
    background-image:none;
    padding-bottom:0px;
}
.nav-item:hover {
    background-image:none;
    padding-bottom:0px;
}
.nav-item > a {
display:block;
color:#ffffff;
padding:8px 16px;
text-decoration:none;
font-size:14px;
border-bottom:1px solid #276815;
margin:0px;


height:auto;
line-height:normal;

border-radius:0px;
}

MyInstanceIDListenerService.java:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mypackagename"
    >

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

    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"   />

    <permission android:protectionLevel="signature"  android:name="mypackagename.permission.C2D_MESSAGE" />
    <uses-permission android:name="mypackagename.permission.C2D_MESSAGE" />


    <application
        android:name=".MyApp"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTemaBase" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".MainActivity"
            android:icon="@drawable/ic_launcher"
            android:launchMode="singleTask">


        </activity>


        <!-- [START gcm_receiver] -->
        <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.REGISTRATION" />
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="mypackagename" />
            </intent-filter>

        </receiver>
        <!-- [END gcm_receiver] -->

        <!-- [START gcm_listener] -->
        <service
            android:name="mypackagename.push.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <!-- [END gcm_listener] -->
        <!-- `enter code here`[START instanceId_listener] -->
        <service
            android:name="mypackagename.push.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>
        <!-- [END instanceId_listener] -->
        <service
            android:name="mypackagename.push.RegistrationIntentService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
    </application>
</manifest>

MyGcmListenerService.java:

import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;

public class MyInstanceIDListenerService extends InstanceIDListenerService {

    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // [END refresh_token]
}

RegistrationIntentService.java:

    public class MyGcmListenerService extends GcmListenerService {

        // [START receive_message]
        @Override
        public void onMessageReceived(String from, Bundle data) {
            String message = data.getString("message");
            Log.d(TAG, "From: " + from);
            Log.d(TAG, "Message: " + message);

            if (from.startsWith("/topics/")) {
                // message received from some topic.
            } else {
                // normal downstream message.
            }

               // sendNotification(message);
            // [END_EXCLUDE]
        }
        // [END receive_message]

Top build.gradle:

public class RegistrationIntentService extends IntentService {

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

    public RegistrationIntentService() {
        super(TAG);
    }

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



        try {
            // [START register_for_gcm]
            // Initially this call goes out to the network to retrieve the token, subsequent calls
            // are local.
            // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
            // See https://developers.google.com/cloud-messaging/android/start for details on this file.
            // [START get_token]
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            // [END get_token]


            // TODO: Implement this method to send any registration to your app's servers.
            //sendRegistrationToServer(token);

sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
            // [END register_for_gcm]
        } catch (Exception e) {
            //Log.d(TAG, "Failed to complete token refresh", e);
            Utils.LogDebug(TAG, "GCM Failed to complete token refresh: " + Utils.getPrintStackTraceToString(e));


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

App build.gradle:

....
dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
        classpath 'com.google.gms:google-services:2.0.0-alpha9'

    }

该插件似乎创建了XML和resourcesid。

以上任何服务或监听器均未被调用。 我做错了什么?

1 个答案:

答案 0 :(得分:2)

我希望您已经从此link

中看到了GCM的示例实现

您是否打过如下注册电话?

if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }

在拨打电话之前检查Google Play服务。

private boolean checkPlayServices() {
    GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (apiAvailability.isUserResolvableError(resultCode)) {
            apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                    .show();
        } else {
            Log.i(TAG, "This device is not supported.");
            finish();
        }
        return false;
    }
    return true;
}