010*_*101 4 service android foreground-service
在 Android 9 上测试前台通知时,我注意到一些非常奇怪的行为。
情况:我有一些前台服务,我不知道它们需要运行多长时间,无论是 1 秒还是一整分钟。最后,当服务完成时,它会调用stopForeground(true). 这曾经在所有 Android 8、9 和 10 设备上都可以正常工作stopForeground(true),即使立即调用,也始终可靠地删除通知。
问题:在Fairphone 3上进行测试(我希望其他人在其他一些设备上遇到过这种情况,因为对我来说这不会在任何模拟器或其他设备上发生),stopForeground没有按预期工作。即使我立即致电,通知也不会立即删除通知,而是始终显示至少 5 秒stopForeground。这 5 秒恰好是可怕错误Context.startForegroundService() 没有调用 Service.startForeground()的确切 5 秒限制- 仍然是一个问题。很奇特!使用下面的代码可以很容易地重现这一点并检查您的设备是否受到影响。
内部AndroidManifest.xml:
<service
android:name="<your package name>.TestService"
android:exported="false" />
Run Code Online (Sandbox Code Playgroud)
班级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());
}
}
Run Code Online (Sandbox Code Playgroud)
最后,只需通过以下方式启动服务(例如单击按钮) startForegroundService(new Intent(this, TestService.class));
有没有其他人遇到过这个问题或者能够用上面的代码重现它?考虑到我正在 Android 9 上进行测试并且行为因 OEM 而不同,我该如何修复甚至只是调试它?
小智 5
最新的安全补丁声称这是正常行为:https : //issuetracker.google.com/issues/147792378
但是我不确定为什么它已经在 Android 9 上发生了。
| 归档时间: |
|
| 查看次数: |
963 次 |
| 最近记录: |