android 前台服务通知始终显示至少5秒

5fjcxozz  于 2023-05-27  发布在  Android
关注(0)|答案(2)|浏览(223)

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

情况:我有一些前台服务,我不知道他们需要运行多长时间,是1秒还是整整一分钟。最后,当服务完成时,它将调用stopForeground(true)。这在所有Android 8,9和10设备上都可以正常工作,其中stopForeground(true),即使立即调用,也总是可靠地删除通知。
问题:在Fairphone 3上测试(我希望其他人在其他设备上遇到过这种情况,因为对我来说,这不会发生在任何模拟器或其他设备上),stopForeground没有按预期工作。即使我立即调用stopForeground,通知也会显示 * 至少5秒 *,而不是立即删除通知。这5秒恰好是可怕的错误Context.startForegroundService() did not then call Service.startForeground() - still a problem的5秒限制。很奇怪!使用下面的代码可以很容易地复制这个并检查您的设备是否受到影响。

内部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而导致行为不同,我如何修复甚至调试它?

s4n0splo

s4n0splo1#

最新的安全补丁声称这是正常行为:https://issuetracker.google.com/issues/147792378
但我不知道为什么它已经在Android 9上发生了。

jum4pzuy

jum4pzuy2#

当你开始你的服务时试试这个,我看到有人在使用它,它起作用了。

ContextCompat.startForegroundService(this, serviceIntent);

下面是链接:https://gist.github.com/codinginflow/1ab6d2689780be6d764215c3a40f2166

相关问题