gcm RegistrationIntentService无注册

时间:2015-09-02 04:39:22

标签: java android google-cloud-messaging message

所以我正在使用gcm,当我尝试注册时,我成功地将令牌发送到我的后端,并将其发送到gcm,回复为200。唯一的问题是200回复​​,但总是说没有注册,并创建失败。我想知道它的前端或后端问题是否会有所帮助。这是我的RegistrationIntentService

package com.example.caesar.gcm;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import java.io.IOException;

public class RegistrationIntentService extends IntentService {

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

    Context mContext = this;

    public String myData="";
    public String streamTitle = "",path="";

    public void onCreate() {
        super.onCreate();
        Log.d("Server", ">>>onCreate()");
    }

    public RegistrationIntentService() {
        super(TAG);
        Log.i(TAG, "ygfuyvjunvvgu");
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, startId, startId);
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        return START_STICKY;
    }

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

        try {

            Log.d(TAG,"HERERERERERER");
            SharedPreferences appPrefs = mContext.getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
            String token = appPrefs.getString("token", "");
            assert token != null;
            if (token.isEmpty()) {
                try {
                    getGCMToken("10426431"); // Project ID: xxxx Project Number: 0123456789 at https://console.developers.google.com/project/...
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            Log.i(TAG, "GCM Registration Token: " + token);
            sendRegistrationToServer(token);
            subscribeTopics(token);
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
        }
        Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }


    private void getGCMToken(final String senderId) throws Exception {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                String token = "";
                try {
                    InstanceID instanceID = InstanceID.getInstance(mContext);
                    token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                    if (token != null && !token.isEmpty()) {
                        SharedPreferences appPrefs = mContext.getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
                        SharedPreferences.Editor prefsEditor = appPrefs.edit();
                        prefsEditor.putString("token", token);
                        prefsEditor.commit();
                    }
                    Log.i("GCM_Token", token);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
    }

    private void sendRegistrationToServer(String token) {

        AsyncHttpClient client = new AsyncHttpClient();

        final RequestParams params = new RequestParams();
        params.put("id", token);

        client.post("", params, new JsonHttpResponseHandler() {

            @Override
            public void onStart() {
                // called before request is started
            }

            public void onSuccess(int statusCode, PreferenceActivity.Header[] headers, JSONObject response) {

            }

            public void onFailure(int statusCode, PreferenceActivity.Header[] headers, JSONObject errorResponse, Throwable e) {
                // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            }

            @Override
            public void onRetry(int retryNo) {
                // called when request is retried
            }
        });
    }

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

}

//服务器端

var options = 
    { 
        method: 'POST',
        uri: 'https://android.googleapis.com/gcm/send',
        headers: {
            'Content-Type': 'application/json',
            'Authorization':'key=VALUE'
        },
        body: JSON.stringify({
        "to" : gcmId,
        "data" : {
            message: message
        },
        })
    }
    request(options, function (error, response, body) {
        if(error) console.log(error);
        console.log("RESPONSE STATUS: " + response.statusCode)
        console.log("BODY: " + body);
        res.json({response: response.statusCode}); 
        });

0 个答案:

没有答案