Android Notification Tap:应用程序不在前台时的片段转换

时间:2015-12-17 04:31:45

标签: android android-fragments android-notifications illegalstateexception fragmentmanager

当应用程序位于前台并收到通知时,活动上的片段转换顺利进行,没有任何问题。如果应用程序在后台运行,则应用程序崩溃,因为片段转换在活动进入前台之前触发!

通知创建代码:

    Intent intent = new Intent(this, MainActivity.class);
    if(newsData == true) {
      intent.putExtra("displayNews", true);
      } else {
      intent.putExtra("displayMessage", true);
      }
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

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

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle(this.getApplicationContext().getString(R.string.app_name))
        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

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

收到通知的MainActivity:

 @Override
    protected void onNewIntent(final Intent intent) {
        final Bundle extras = intent.getExtras();
        if (intent.getExtras().get("displayNews") != null) {
          showFragment(context, "newsFragment", false);
        } else {
            showFragment(context, "messageFragment", false);
        }
    }

    public void showFragment(final FragmentActivity context, final String selectedItem, final boolean reverseAnimation) {

        final Fragment switchFragment = getFragment(selectedItem);
        final FragmentManager fragmentManager = context.getSupportFragmentManager();
        final Fragment fragment = fragmentManager.findFragmentByTag(selectedItem);
        if (fragment == null) {
          final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
          if (!reverseAnimation) {
            fragmentTransaction.setCustomAnimations(R.anim.abc_fade_in, R.anim.slide_out_left);
          } else {
            fragmentTransaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
          }
          fragmentTransaction.replace(R.id.content_frame, switchFragment, selectedItem);
          fragmentTransaction.commit();
        }
  }

如何在MainActivity中等待活动在开始片段转换之前到达前台?

错误日志:

Application has been shut down. Please inspect exception trace for more details.
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

2 个答案:

答案 0 :(得分:1)

最终使用正确的解决方案(如评论中所示)。

fragmentTransaction.replace(R.id.content_frame, switchFragment, selectedItem);
      fragmentTransaction.commitAllowingStateLoss();

答案 1 :(得分:1)

在转换之前,您可以等到onStart(),因为那时UI将是可见的(并且您似乎正在制作动画)。使用布尔值来跟踪您是否在onStart()onStop()之间 - 如果是,请执行转换;如果没有,请存储有关待处理转换的一些信息,并等待onStart()