如何从gcmIntentService转移到片段

时间:2016-03-23 10:05:31

标签: android android-fragments google-cloud-messaging fragment

我想在收到通知时打开通知片段。一旦我点击接收通知,我想转移到通知片段。

这是我的代码:

if(chatType.equals("7")){

    notification.contentView = contentView;
    /*  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, NotificationsActivity.class).putExtra("json_msg",msg).
                    setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
                            |Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT);
    notification.contentIntent = contentIntent;
    */

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent.putExtra("json_msg",msg),0);
    notification.contentIntent = contentIntent;

    /*
    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.containerView,new NotificationsFragment()).commit();
    */

    // notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
    notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
    notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
    notification.defaults |= Notification.DEFAULT_SOUND; // Sound
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(NOTIFICATION_ID, notification);
} else {
    notification.contentView = contentView;
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ChatActivity.class).putExtra("json_msg",msg).
                        setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
                                |Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT);
    notification.contentIntent = contentIntent;

    // notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
    notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
    notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
    notification.defaults |= Notification.DEFAULT_SOUND; // Sound
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

1 个答案:

答案 0 :(得分:1)

您需要从设置通知意图的活动中启动片段。因此,假设您的通知打开了MainActivity,您可以在onCreate或onNewIntent中调用此类方法

所以例如

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

    public void loadNotificationFragment() {
    if (getIntent() != null) {
        getSupportFragmentManager()
                .beginTransaction() 
                .replace(R.id.fragment_container, NotificationFragment.newInstance(getIntent().getStringExtra("jso_msg")))
                .addToBackStack(null)
                .commit();
    }
}