1

我有一个设置,我的活动启动服务并通过控制服务行为方式的意图发送值。这些变量可以在服务的整个生命周期中发生变化,并且服务会将更新推送回活动 UI。如果我退出活动并重新启动它,它将请求服务更新以获取当前值。如果我通过主屏幕重新启动活动,或者我使用最近的应用程序菜单,这工作正常。但是,如果我通过我为服务设置的在前台运行持续通知启动活动,则服务会在启动时将自身重新设置为原始值。

这是我在前台运行的代码,我认为没有其他任何东西会对这个问题产生影响。

//Create notification and set to run in forground
    Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),
            System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.app_name),
            "Running Noise Based", pendingIntent);
    startForeground(ONGOING_NOTIIFICATION, notification);

更新 3:

将标志 Intent.FLAG_ACTIVITY_NEW_TASK、Intent.FLAG_ACTIVITY_CLEAR_TOP 和 Intent.FLAG_ACTIVITY_SINGLE_TOP 添加到通知意图解决了问题。我不知道为什么这些修复它。如果有人能告诉我为什么会发生这种情况,请这样做。这是有效的新代码。

//Create notification and set to run in forground
        Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, getText(R.string.app_name),
                "Running Noise Based", pendingIntent);
        startForeground(ONGOING_NOTIIFICATION, notification);
4

0 回答 0