GCM适用于build.gradle 1.4.0但不适用于1.3.0

时间:2015-11-30 11:03:04

标签: android gradle google-cloud-messaging google-play-services

当构建评分者是com.google.gms:google-services:1.4.0-beta3时,GCM正在生成令牌,但当我将其更改为com.google.gms时:google-services:1.3.0-beta1它会停止生成“令牌。 当我在build.gradle(app)中使用1.4.0-beta3“我设置”com.google.android.gms:play-services-gcm:8.1.0“

我提到了google文档。

有人可以帮我弄明白我哪里错了吗? 这是我的源代码: 1)的build.gradle(项目):

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.google.gms:google-services:1.3.0-beta1'
        //classpath 'com.google.gms:google-services:1.4.0-beta3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

2)这是build.gradle(app):

    buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.yembrace.android.app"
        minSdkVersion 21
        targetSdkVersion 21
        maxSdkVersion 22
        versionCode 4
        versionName "1.0.3"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'

    compile 'com.google.android.gms:play-services-plus:7.5.0'
    compile "com.google.android.gms:play-services-gcm:7.5.0"

//    compile 'com.google.android.gms:play-services-plus:8.1.0'
//    compile "com.google.android.gms:play-services-gcm:8.1.0"


    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.android.support:recyclerview-v7:23.1.0'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.android.support:cardview-v7:23.1.0'

    //beacons sdk
    compile 'com.estimote:sdk:0.8.8@aar'

    compile 'com.github.clans:fab:1.6.2'

    //Cards
    compile 'com.github.gabrielemariotti.cards:cardslib-cards:2.1.0'


    compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
        transitive = true;
    }
}

3)清单文件:

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

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="com.yembrace.yembarce.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

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

    <application
        android:name=".AppController"
        android:allowBackup="true"
        android:icon="@drawable/app_logo"
        android:label="@string/app_name"
        android:theme="@style/AppCompatTheme"
        android:screenOrientation="portrait">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!-- - Receivers -->
        <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.yembrace.yembarce" />
            </intent-filter>
        </receiver>
        <receiver android:name=".Receivers.BeaconReceiver">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
            </intent-filter>
        </receiver>
        <receiver android:name=".Receivers.LocationReceiver">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />

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

        <!-- Services -->
        <service
            android:name=".Services.MyGcmListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:name=".Services.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>
        <service
            android:name=".Services.RegistrationIntentService"
            android:exported="false" />
        <service android:name=".Services.BeaconService" />
        <service
            android:name="com.estimote.sdk.service.BeaconService"
            android:exported="false" />

        <action android:name="android.location.PROVIDERS_CHANGED" />

        <service
            android:name=".Services.LocationService"
            android:exported="false" />
        <!-- Activities -->


        <!-- Launcher Activity -->
        <activity
            android:name=".Activities.Launcher"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Login Activity -->
        <activity
            android:name=".Activities.LoginActivity"
            android:label="@string/titleActivityLogin"
            android:theme="@style/ThemeOverlay.MyNoTitleActivity" />
        <activity
            android:name=".Activities.MainActivity"
            android:label=""
            />
        <activity
            android:name=".Activities.ShopActivity"
            android:label=""
            />
        <activity
            android:name=".Activities.ItemActivity"
            android:label=""
            />
        <activity
            android:name=".Activities.ProfileActivity"
            android:label="@string/titleActivityProfile"
            />
        <activity
            android:name=".Activities.AboutActivity"
            android:label="@string/titleActivityAbout"
            />

        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="9e91d69acd5e717118f65608d8b4bae54dd4ab43" />

        <!--<activity
            android:name=".Activities.CheckoutActivity"
            android:label="@string/title_activity_checkout"
            android:theme="@style/AppTheme"></activity>-->
    </application>

</manifest>

4)RegistrationIntentService.java

public class RegistrationIntentService extends IntentService {

    private static final String TAG = "RegIntentService";
    private static final String[] TOPICS = {"global"};
    private SharedPreferences sharedPreferences = AppController.getAppContext().getSharedPreferences("app_pref", MODE_PRIVATE);
    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.
            // [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);

            // Subscribe to topic channels
            subscribeTopics(token);

            // You should store a boolean that indicates whether the generated token has been
            // sent to your server. If the boolean is false, send the token to your server,
            // otherwise your server should have already received the token.
            sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, true).apply();
            // [END register_for_gcm]
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            // If an exception happens while fetching the new token or updating our registration data
            // on a third-party server, this ensures that we'll attempt the update at a later time.
            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);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    /**
     * Persist registration to third-party servers.
     *
     * Modify this method to associate the user's GCM registration token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(final String token) {
        // Add custom implementation, as needed.
        Log.d("TAG","GCM Token "+token);
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                Config.user_gcm_register,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TAG",response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("TAG",error.toString());
                    }
                }){

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> params = new HashMap<>();
                //params.put("Authorization", Config.authorization);
                return params;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                Log.d("TAG","user Id "+sharedPreferences.getString("userID","null")+",GCM:"+token);
                params.put("PublicUserID",sharedPreferences.getString("userID","null"));
                params.put("GCMRegistrationToken",token);
                return params;
            }
        };
        AppController.getInstance().addToRequestQueue(stringRequest);
    }

    /**
     * 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) throws IOException {
        GcmPubSub pubSub = GcmPubSub.getInstance(this);
        for (String topic : TOPICS) {
            pubSub.subscribe(token, "/topics/" + topic, null);
        }
    }
    // [END subscribe_topics]

}

5)这是我称之为GCM的地方:

private void GCMRegister() {
        Log.d("TAG","In gcm rregister in login");
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                boolean sentToken = sharedPreferences.getBoolean(Config.SENT_TOKEN_TO_SERVER, false);
                if (sentToken) {
                    Log.d(TAG, "register");
                } else {
                    Log.d(TAG, "token error");
                }
            }
        };


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

1 个答案:

答案 0 :(得分:0)

我能够通过在清单文件中添加以下内容来解决此问题:

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