从Google云消息接收器传递intent extras到Activity为空值

3
我有一个广播接收器,用于监听云消息。我可以正常显示通知,但当用户点击通知时,我希望使用intent extras将他们路由到正确的活动页面。但extras始终为空。
在调试过程中,我可以验证传递给pending intent的intent确实具有extras。
我尝试在活动的onCreate()方法中捕获意图。
***编辑添加可运行代码,有几点需要注意,如果任务已经启动,则不能保证oncreate()方法被调用,因此最好在onresume方法中获取extras。我需要设置意图和pending intent上的标志。
@EReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {

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

@Pref
public MyPrefs_ myPrefs;

@Override
public void onReceive(Context context, Intent intent) {

    Log.d(TAG, "received gcm message");

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    this.ctx = context;

    String messageType = gcm.getMessageType(intent);

    if (messageType != null) {

        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

        }
        else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

        }
        else if (messageType.equalsIgnoreCase("gcm")) {
            myPrefs.notification().put(true);
            handleNotification(intent);
        }
    }
    setResultCode(Activity.RESULT_OK);
}

private void handleNotification(Intent intent) {

    Bundle bundle = intent.getExtras();

    String typeString = bundle.getString("type");
    String icon = bundle.getString("icon");

    String title = null;
    String body = null;
    Class<?> intentClass = null;
    Integer intentExtraId = null;

    if (typeString == null)
        return;

    int type = Integer.parseInt(typeString);

    switch (type) {

    case 1:

        intentClass = FriendsActivity_.class;

        title = bundle.getString("username");

        break;

    case 2:

        intentClass = UserProfileActivity_.class;

        title = bundle.getString("username");

        intentExtraId = Integer.parseInt(bundle.getString("user_id"));

        break;




    }


    mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);


Intent i = new Intent();
    i.setClass(ctx, intentClass);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP     | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.putExtra("gcm", true);
    if (intentExtraId != null) {

        i.putExtra("id", intentExtraId);
    }

    int requestID = (int) System.currentTimeMillis();

    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, requestID, i,     PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx);

    mBuilder.setSmallIcon(R.drawable.ic_stat_u);

    Bitmap bmp = null;

    try {
        bmp = Ion.with(ctx, ctx.getResources().getString(R.string.image_container) + icon).asBitmap().get();
    }
    catch (InterruptedException e) {

        e.printStackTrace();
    }
    catch (ExecutionException e) {

        e.printStackTrace();
    }

    if (icon != null) {
        mBuilder.setLargeIcon(bmp);
    }

    mBuilder.setContentTitle(title).setStyle(new NotificationCompat.BigTextStyle().bigText(body))
            .setContentText(body);

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

}

}

活动

 @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

@Override
protected void onResume() {

    super.onResume();

    Integer newId = getIntent().getExtras().getInt("id");

    id = newId;


}
3个回答

3

这是用于获取PendingIntent的调用:

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

如果系统中已经存在匹配的PendingIntent,则此调用将只返回该项。它可能包含或不包含您想要的额外信息。要确保使用您的额外信息,您必须确保更新任何当前的PendingIntent,如下所示:
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

嗨David,感谢您的回复。将该标志添加到待处理意图确实会发送额外信息,但我只能在onresume或onstart中获取它们,而不是在我通常获取额外信息的oncreate中,这似乎是奇怪的行为,请问您有任何想法吗? - Brian
发布你的清单文件,我来看看。同时也请发布你在onCreate()中获取额外信息所使用的代码。 - David Wasser

1

你可以尝试使用这个链接。链接为:https://developers.google.com/cloud-messaging/android/start

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
        sendNotification(message)
    } else {
        // normal downstream message.
    }

    // ...
}

///////// 添加这个方法

private void sendNotification(String message) {
    Intent intent = new Intent(this, ListLocations.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_park_notification)
            .setContentTitle("Parkuest Message")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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

1
你可以制作简单的通知,并在其上设置onclick。请将下面示例中的YourMainActivity处替换为您的活动。
public void createNotification(Context context, String payload, String message) {
    try {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher, message, System.currentTimeMillis());
        // Hide the notification after its selected
        // notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.ledARGB = 0xff00ff00;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;

        Intent intent = new Intent(context, YourMainActivity.class);
        intent.putExtra("payload", payload);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("NotifID", 1);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(context, "Message", message, pendingIntent);
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);
    } catch (Exception e) {

            Log.e(this.getClass().getSimpleName(), e.getMessage(), e);

    }
}

如果有帮助,请标记为“真实”或投票支持


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接