Android - 如何为 API-28 使用 startForegroundService() 和 startForeground()?

标签 android service android-service android-8.0-oreo foreground-service

我目前正在研究如何创建一个 float 的前台泡泡聊天头服务。
但是,我注意到我尝试使用的所有库都不适用于 API-28。
我相信这是由于提到的新限制 here in the Android docs .

它基本上指出,如果我正在调用在前台显示内容的服务:
我必须调用 startForegroundService() 而不是 startService()
/>
此外,它指出:
“在系统创建服务后,应用程序有五秒钟的时间调用服务的 startForeground() 方法来显示新服务的用户可见通知。”< br/>
我相信这可能是我无法让这些前台 chathead 库工作的原因。
有人可以举例说明我应该如何实现这些吗?
请谢谢!

最佳答案

@Override
public void onCreate() {
    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Android O requires a Notification Channel.
    if (Build.VERSION.SDK_INT >= 26) {
        CharSequence name = getString(R.string.app_name);
        // Create the channel for the notification
        @SuppressLint("WrongConstant")
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW);
        // Set the Notification Channel for the Notification Manager.
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(mChannel);
        }

        startForegroundService(new Intent(ForegroundService.this, ForegroundService.class));
        //We only need to call this for SDK 26+, since startForeground always has to be called after startForegroundService.
        startForeground(NOTIFICATION_ID, getNotification());
    }
    else {
        startService(new Intent(ForegroundService.this, ForegroundService.class));
    }

此外,该项目是开始实现 ForegroundService 的良好基础:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdatesForegroundService

关于Android - 如何为 API-28 使用 startForegroundService() 和 startForeground()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55136846/

相关文章:

android - 如何在android中添加对项目的引用?

android - Jetpack Compose 中没有涟漪效应

amazon-web-services - 将端口添加到现有的kubernetes服务

.net - 使用 C# 更改 Windows 服务凭据的最佳方法是什么

java - Android 问答游戏 - 每个问题的倒数计时器

android - 发送带有参数的 JSON 对象时出现 JSON 解析错误

Angular 如何在服务中使用 Websocket?

android - IAE : Service not registered on unbindService after Service. stopSelf

android - 即使应用程序已关闭,如何每天在特定时间显示通知?

android - 使用警报管理器启动服务,但前提是主应用程序未运行