2

我开发了一个应用程序,它将向注册的 Android 设备发送通知。

为此,我需要向 Google Cloud Messaging Service 注册设备。这会给我RegistrationId。

它在模拟器中收到了registrationId,但在设备中没有。

可能是什么原因 ?

//on MainActivity.java
//This code i am calling in onCreate()
//---------------------------------------
GCMRegistrar.checkDevice(getBaseContext());

        GCMRegistrar.checkManifest(getBaseContext());

        registerReceiver(mHandleMessageReceiver, new IntentFilter("dotsandcoms.android.siteuplitenew.DISPLAY_MESSAGE"));

        regId = GCMRegistrar.getRegistrationId(getBaseContext());

        if (regId.equals("")) {

            GCMRegistrar.register(getBaseContext(), "677416186780");

        } else {

            Log.v("siddharth", "Already registered");

            System.out.println("Registration ID : " + regId);

        }
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {

    @Override

    public void onReceive(Context context, Intent intent) {

        String newMessage = intent.getExtras().getString("message");

        System.out.println(newMessage + "\n");

    }
};

//-----------------------------------------------------------------
//This is the GCMIntentService code
//-------------------------------------------------------------------

public class GCMIntentService extends GCMBaseIntentService {

@Override
protected void onError(Context arg0, String arg1) {
    // TODO Auto-generated method stub
    Log.i(TAG, "Error = " + arg1.toString());
}

@Override
protected void onMessage(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    String message = arg1.getStringExtra("message");
    generateNotification(arg0, message);
}

@Override
protected void onRegistered(Context arg0, String arg1) {
    // TODO Auto-generated method stub
    Log.i(TAG, "Device registered: regId = " + arg1.toString());
    System.out.println("Registration ID : " + arg1.toString());
}

@Override
protected void onUnregistered(Context arg0, String arg1) {
    // TODO Auto-generated method stub
    Log.i(TAG, "on unregId = " + arg1.toString());
}

private static void generateNotification(Context context, String message) {
    int icon = R.drawable.icon;

    long when = System.currentTimeMillis();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MainActivity.class);

    // set intent so it does not start a new activity

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, notification);
}
4

0 回答 0