Android 通过通知项重新打开后台应用程序

Android 通过通知项重新打开后台应用程序,android,background,notifications,Android,Background,Notifications,我有一个带有标签和通知栏的应用程序, 当我将其发送到后台时(单击主页按钮) 并尝试通过单击 通知栏,应用程序将重新启动(上次选择 标签丢失) 当我按住home(主页)按钮时,如果应用程序处于 单击背景并从中选择它,或单击 主屏幕上的应用程序图标,以前的状态为 按默认值还原(已选择正确的选项卡) 我认为通知的意图是错误的,但我 我不知道怎么修 简而言之:如何让后台应用程序返回到 在单击通知条目时显示前台 谢谢 您是否按照中的建议实施onSaveInstanceState方法 当您暂停应用程序并立即

我有一个带有标签和通知栏的应用程序, 当我将其发送到后台时(单击主页按钮) 并尝试通过单击 通知栏,应用程序将重新启动(上次选择 标签丢失)

当我按住home(主页)按钮时,如果应用程序处于 单击背景并从中选择它,或单击 主屏幕上的应用程序图标,以前的状态为 按默认值还原(已选择正确的选项卡)

我认为通知的意图是错误的,但我 我不知道怎么修

简而言之:如何让后台应用程序返回到 在单击通知条目时显示前台


谢谢

您是否按照中的建议实施onSaveInstanceState方法


当您暂停应用程序并立即返回时,应用程序可能仍挂在后台的内存中。但是,您不能依赖于此,因此每次进入后台时,您都应该像当前打开的选项卡一样保存状态,并在重新激活时将其还原。

将这两行放在下面。这将恢复当前暂停的活动:

notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
公共静态布尔值isApplicationRunningBackground(最终上下文){
ActivityManager am=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
List tasks=am.getRunningTasks(am.getrunningappprocesss().size());
用于(RunningTaskInfo RunningTaskInfo:tasks){
if(runningTaskInfo.topActivity.getPackageName().equals(context.getPackageName())){
MyLog.i(“UTIL”、“packageName:+runningTaskInfo.topActivity.getPackageName());
i(“UTIL”、“className”+runningTaskInfo.topActivity.getClassName());
返回true;
}
}
返回false;
}
意向通知意向;
if(Util.isApplicationRunningBackground(上下文)){
notificationIntent=新的意图(上下文,MainView.class);
}否则{
notificationIntent=新的意图(上下文,Splash.class);
}

在意图中使用两个标志

intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

我也遇到过同样的问题,并极力寻找答案,但这里有一个诀窍:与其尝试使用通知意图以保存的状态重新启动应用程序,不如使用通知意图打开一个空白活动,然后在活动的onCreate()方法中,只需完成()即可。这将带您回到应用程序上上次查看的活动。

请注意,从通知触发
意图
始终会创建
活动的新实例
;不能直接返回到现有实例。恕我直言,我相信您可以在
活动中使用CLEAR_top(和
onNewIntent
)等标志之一来确保保留现有实例。这非常有效。但是最好使用常量notifyIntent.setAction(Intent.ACTION_MAIN);notifyIntent.addCategory(Intent.CATEGORY_启动器);天哪,几个月来我一直在寻找解决方案,但这真是太棒了。这看起来像是作弊,但很可怕。
public static boolean isApplicationRunningBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(am.getRunningAppProcesses().size());
    for (RunningTaskInfo runningTaskInfo : tasks) {
        if (runningTaskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
            MyLog.i("UTIL", "packageName:" + runningTaskInfo.topActivity.getPackageName());
            MyLog.i("UTIL", "className" + runningTaskInfo.topActivity.getClassName());
            return true;
        }
    }
    return false;
}

Intent notificationIntent;
        if (Util.isApplicationRunningBackground(context)) {
            notificationIntent = new Intent(context, MainView.class);
        } else {
            notificationIntent = new Intent(context, Splash.class);
        }
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);