android - GCM适用于build.gradle 1.4.0,但不适用于1.3.0

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

当构建评分器为com.google.gms:google-services:1.4.0-beta3时,GCM会生成 token ,但是当我将其更改为com.google.gms:google-services:1.3.0-beta1时,它将停止生成“ token 。
当我使用1.4.0-beta3时,我在build.gradle(app)中设置了“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) list 文件:
    <?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);
    }

最佳答案

我可以通过在 list 文件中添加以下内容来解决此问题:

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

关于android - GCM适用于build.gradle 1.4.0,但不适用于1.3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997094/

相关文章:

android - 即使启用了所有位置服务,Google 位置服务 getBestProvider 也会返回 null

使用 ProGuard 的 Android Export 应用程序

java - 我可以通过常规 J​​ava main 方法从 Android 项目运行纯 Java 代码的子集吗?

java - 无法应用插件 [id 'forge' ]

php - GoogleCloudMessaging PHP 脚本总是返回无效注册

java - 从 Bundle getParcelable 有时会导致 java android 中的 BadParcelableException

java - 获取没有照片的电话联系人,以便将它们保存在 DataOutputStream(vcf 格式)中

android - 如何在根 gradle.build 脚本中指定常见的 gradle 属性

android - GCM 在 Android 4 以下收不到消息

android - 项目树中的 google-services.json 位置