Android GCM注册ID

时间:2012-09-03 09:43:44

标签: android google-cloud-messaging

我想使用GCM。我试着在客户端跟进:

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.test.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.test.permission.C2D_MESSAGE" />

<application android:icon="@drawable/ic_launcher"  android:label="@string/app_name" >

<activity android:screenOrientation="portrait"
            android:name=".MainActivity"
            android:label="@string/app_name"
             android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" 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.example.test" />
        </intent-filter>
    </receiver>
    <service android:name=".GCMIntentService" android:enabled="true" />
    </application>
</manifest>

的活动:

package com.example.test;



import com.google.android.gcm.GCMRegistrar;

import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.WindowManager;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gcmRelated();
    }

    private void gcmRelated() {
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        Toast.makeText(this, regId, 10000).show();

        if (regId.equals("")) {
          GCMRegistrar.register(this, "609612932495");
        } else {
          Log.v("Register", "Already registered");
        }


    }



}

GCMIntentService.java:

package com.example.test;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import java.util.logging.Logger;

public class GCMIntentService extends GCMBaseIntentService
{
    private static PowerManager.WakeLock sWakeLock;
    private static final Object LOCK = GCMIntentService.class;
    private static final String GCM_SENDER_ID = "609612932495";
    private static final String GCM_INTENT_FILTER = "com.example.test.GCM_MESSAGE";
    private static final String MESSAGE_TYPE = "Type";
    private static final String MESSAGE_CONTENT = "Body";
    private static Logger log = Logger.getLogger(GCMIntentService.class.getName());

    public GCMIntentService()
    {
        super(GCM_SENDER_ID);
    }

    static void runIntentInService(Context context,Intent intent)
    {
        synchronized(LOCK)
        {
            if (sWakeLock == null)
            {
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"sc_wakelock");
            }
        }
        sWakeLock.acquire();
        intent.setClassName(context,GCMIntentService.class.getName());
        context.startService(intent);
    }

    @Override protected void onRegistered(Context context,String registrationId)
    {
        log.warning("From GCMIntentService: Device successfully registered as "+registrationId);

    }

    @Override protected void onUnregistered(Context context,String registrationId)
    {
        log.warning("From GCMIntentService: Device successfully unregistered");

    }

    @Override protected void onMessage(Context context,Intent messageIntent)
    {
        log.warning("From GCMIntentService: Game update notice received");

    }

    @Override protected void onDeletedMessages(Context context,int total)
    {
        log.warning("From GCMIntentService: Server deleted "+Integer.toString(total)+" pending messages");
    }

    @Override public void onError(Context context,String errorId)
    {
        log.warning("From GCMIntentService: Error "+errorId);

    }

    @Override protected boolean onRecoverableError(Context context,String errorId)
    {
        log.warning("From GCMIntentService: Recoverable error "+errorId);
        return(super.onRecoverableError(context,errorId));
    }
}

它没有显示任何错误。 GCMRegistrar.getRegistrationId(this)始终返回“”(空字符串)。所以,它总是试图注册,我从来没有registerId。

还有什么要做的吗?

此外,在实现服务器端代码时,是否需要发送此寄存器ID并将所有ID保存在数据库中并发送它们?

1 个答案:

答案 0 :(得分:3)

    public class GCMIntentService extends GCMBaseIntentService {

    @SuppressWarnings("unused")
    private final String TAG = "GCMIntentService";

    public GCMIntentService() {

        super("GCM_ID");
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    public void generateNotification(Context context, String message) {
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher, message, when);
        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, SamplePushActivity.class);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS;
        notificationManager.notify(0, notification);
    }

    @Override
    protected void onError(Context arg0, String arg1) {

    }

    @Override
    protected void onMessage(Context arg0, Intent arg1) {

        Resources res = getResources();
        Log.d("GCM", "RECIEVED A MESSAGE");

        // Get the data from intent and send to notificaion bar

        System.out.println("MEssage Recieved :" + arg1.getStringExtra("message"));
        System.out.println("Data Recieved :" + arg1.getExtras().getString("collapse_key"));

        // generateNotification(arg0, arg1.getStringExtra("state"));
        // generateNotification(arg0, arg1.getStringExtra("message"));
        generateNotification(arg0, res.getString(R.string.assignment_new, "arg1", "arg2"));
        // String notifyMessage = arg1.getStringExtra("collapse_key");
        // if
        // (arg1.getStringExtra("collapse_key").equalsIgnoreCase("NOTIFICATION_ASSIGNMENT"))
        // {
        // generateNotification(arg0, arg1.getStringExtra("message"));
        // }
    }

    @Override
    protected void onRegistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub
    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub
    }

public class SamplePushActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        TextView regNumber = (TextView) findViewById(R.id.textView1);

        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);

        if (GCMRegistrar.isRegistered(this)) {
            Log.d("info", GCMRegistrar.getRegistrationId(this));
        }

        final String regId = GCMRegistrar.getRegistrationId(this);
        regNumber.setText(regId);

        if (regId.equals("")) {
            // replace this with the project ID
            System.out.println("registration ID is " + regId);
            GCMRegistrar.register(this, "GCM_ID");
            Log.d("info", GCMRegistrar.getRegistrationId(this));
            System.out.println("Get Reg ID: " + GCMRegistrar.getRegistrationId(this));
            regNumber.setText(regId);
        } else {
            Log.d("info", "already registered as" + regId);
        }
    }

<uses-sdk android:minSdkVersion="8" />

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

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

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="in.android.gcm.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".SamplePushActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        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="in.android.gcm" />
        </intent-filter>
    </receiver>

    <service android:name=".GCMIntentService" />
</application>