首页 > 解决方案 > 前台服务通知始终显示至少 5 秒

问题描述

在 Android 9 上测试前台通知时,我注意到一些非常奇怪的行为。

情况:我有一些前台服务,我不知道它们需要运行多长时间,无论是 1 秒还是整分钟。最后,当服务完成时,它会调用stopForeground(true). 这在所有 Android 8、9 和 10 设备上都可以正常工作stopForeground(true),即使立即调用,也总是可靠地删除通知。

问题:在Fairphone 3上进行测试(我希望其他人在其他设备上遇到过这种情况,因为对我来说,这在任何模拟器或其他设备上都没有发生),stopForeground没有按预期工作。即使我立即打电话,通知也总是显示至少 5 秒stopForeground,而不是立即删除通知。这 5 秒恰好是可怕错误Context.startForegroundService() 的确切 5 秒限制,然后没有调用 Service.startForeground() - 仍然是一个问题。很奇特!使用下面的代码很容易重现这一点并检查您的设备是否受到影响。

内部AndroidManifest.xml

<service
    android:name="<your package name>.TestService"
    android:exported="false" />

TestService.java

package <your package name>;

import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

@TargetApi(Build.VERSION_CODES.O)
public class TestService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showNotification();
        stopForeground(true);
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void showNotification() {
        String channelId = "TEST";
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager.getNotificationChannel(channelId) == null)
            notificationManager.createNotificationChannel(new NotificationChannel(channelId, "TEST NOTIFICATIONS", NotificationManager.IMPORTANCE_DEFAULT));
        startForeground(1, new NotificationCompat.Builder(this, channelId).setContentText("TEST NOTIFICATION").build());
    }
}

最后,只需通过以下方式启动服务(例如单击按钮)startForegroundService(new Intent(this, TestService.class));

有没有其他人遇到过这个问题或者能够用上面的代码重现它?考虑到我在 Android 9 上进行测试并且行为因 OEM 而不同,我该如何修复甚至只是调试它?

标签: androidserviceforeground-service

解决方案


最新的安全补丁声称这是正常行为: https ://issuetracker.google.com/issues/147792378

但是我不确定为什么它已经在 Android 9 上发生了。


推荐阅读