接收android推送通知

时间:2015-10-04 16:47:41

标签: android google-cloud-messaging

我已获得设备的注册ID,当我尝试从我的服务器向我的应用发送推送通知时,我收到了成功的消息:

{" multicast_id": SOME_ID ,"成功":1,"失效":0," canonical_ids&# 34;:0,"结果":[{" MESSAGE_ID":" 0: SOME_ID "}]}

但我的应用程序没有显示任何通知或警报。我一直在网上尝试超过6种不同的指南,但仍无法从我的应用中找到通知方式。

即使没有申请的用户,如何接收此通知并在我的应用中将其显示为推送通知?

public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    public GcmIntentService() {
        super("GcmIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("New Message!");
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
}

广播接收器

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

1 个答案:

答案 0 :(得分:1)

1.1000000000000000888178419700125232338905334472656250000

和......

public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");

    // showing an alert activity if there is an active activity 

    Intent pushReceivedIntent = new Intent("Push");
    pushReceivedIntent.putExtras(data);

    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    if(componentInfo.getPackageName().equalsIgnoreCase(Constants.APP_PACKAGE)){
        getApplicationContext().sendBroadcast(pushReceivedIntent);
    }
    else{
        // showNotification(data);
    }
}

这是我使用的Intent服务,

private void showNotification(Bundle data) {
    String message = data.getString("message");

    Intent intent = new Intent(this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}

现在,在你的活动onResume方法中,你需要添加接收器。

public class RegistrationIntentService extends IntentService {

private static final String TAG = "RegIntentService";
private static final String gcm_defaultSenderId = "1234556";

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(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);

        sharedPreferences.edit().putBoolean("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("SENT_TOKEN_TO_SERVER", false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent("REGISTRATION_COMPLETE");
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

private void sendRegistrationToServer(String token) {
    Log.d("token ", token);
    //TODO: Send This to server
}

此外,还要检查设备令牌。