2

当我收到推送时,我会开始一项决定我们做什么的活动。要生成通知,我使用以下代码:

public class MyGcmBroadcastReceiver extends BroadcastReceiver {

private Context ctx;
private static final int NOTIFICATION_ID = 1;
private NotificationCompat.Builder builder;
private NotificationManager mNotificationManager;

@Override
public void onReceive(Context context, Intent intent) {
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    ctx = context;
    String messageType = gcm.getMessageType(intent);
    if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
        // sendNotification("Send error: " + intent.getExtras().toString(), "", "");
    } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
        // sendNotification("Deleted messages on server: " + intent.getExtras().toString(), "", "");
    } else {
        String alert = intent.getExtras().getString("alert");
        String key = intent.getExtras().getString("k");
        String id = (String) intent.getExtras().get("i");
        sendNotification(alert, key, Long.parseLong(id));
    }
    setResultCode(Activity.RESULT_OK);
}

// Put the GCM message into a notification and post it.
private void sendNotification(String msg, String key, long id) {
    mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(ctx, FakePushActivity_.class);
    notificationIntent.putExtra(Constants.EXTRA_ORDER_ID, id);
    notificationIntent.putExtra(Constants.EXTRA_KEY_PUSH, key);
    notificationIntent.putExtra(Constants.EXTRA_MSG_PUSH, msg);

    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);

    // long[] vibraPattern = { 0, 500, 250, 500 };
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.ic_launcher)
            .setAutoCancel(true)
            .setContentTitle(ctx.getString(R.string.app_name))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

}

MyFakePushActivity是一个简单的活动,它测试一些参数以了解什么活动开始。例如,如果应用程序正在运行,那么我们将显示一个DialogFragmentelse 我们运行该应用程序。应用程序运行时一切正常。我可以看到推送,当我点击推送时,我的活动开始了。

如果我通过推送唤醒应用程序,没关系,但下一次推送不再启动 FakePushActivity。我可以看到并单击它,但单击时没有任何反应(推送只会消失)。并且用户必须再次启动应用程序才能接收新的推送。

似乎有问题,PendingIntent但我的日志中没有错误。

你知道是什么问题吗?

提前谢谢


[[ EDIT ]]:我终于找到了解决方案,但我不明白它为什么有效。如果有人可以解释我,因为我发现这个关于意图标志的故事不是很清楚。

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

1 回答 1

0

检查这个:FLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_SINGLE_TOP

于 2013-10-16T11:24:08.577 回答