gpt4 book ai didi

安卓通知点击 : Fragment transition when app not in foreground

转载 作者:行者123 更新时间:2023-11-29 20:14:01 25 4
gpt4 key购买 nike

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

通知创建代码:

    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 中等待 Activity 在开始 fragment 转换之前到达前台?

错误日志:

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

最佳答案

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

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

关于安卓通知点击 : Fragment transition when app not in foreground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34326654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com