小编Lov*_*oid的帖子

如何在点击推送通知消息时打开特定片段?

我想在点击推送通知消息时打开特定片段。在我的情况下,当通知发生时片段是打开的。但我想在点击通知消息而不是到达消息时打开片段。

这是我的 sendNotification() 方法:-

 private void sendNotification(String msg) {

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


        Intent intent = new Intent(this, MainActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("data", "fromoutside");
        getApplicationContext().startActivity(intent);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);


        NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(getNotificationIcon())
                .setContentTitle("Telepoh")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

        mBuilder.setContentIntent(contentIntent);
        mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
        mBuilder.setAutoCancel(true);


        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    } 
Run Code Online (Sandbox Code Playgroud)

这是我的 onNewIntent() 方法,它在我打开片段的 MainActivity 中覆盖:-

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Fragment fragment = new NotificationActivity();
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();

    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我想在点击推送通知消息时打开这个片段,但在我的情况下,当推送通知消息到达时片段是打开的。

android push-notification android-intent android-pendingintent google-cloud-messaging

3
推荐指数
1
解决办法
4410
查看次数