【问题标题】:Android - How to use startForegroundService() and startForeground() for API-28?Android - 如何将 startForegroundService() 和 startForeground() 用于 API-28?
【发布时间】:2019-03-13 07:55:09
【问题描述】:

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

它本质上是说,如果我正在调用一个在前台显示事物的服务:
我必须调用 startForegroundService() 而不是 startService()

此外,它指出:
“系统创建服务后,应用程序有五秒钟时间调用服务的startForeground() 方法以显示新服务的用户可见通知。”

我相信这可能是我无法让这些前台聊天头库工作的原因。

有人可以提供我应该如何实现这些的示例吗?
请,谢谢!

【问题讨论】:

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


    【解决方案1】:
    @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

    【讨论】:

    • 那么您的意思是,对于 API-26+,如果我正在启动前台服务,我还需要创建一个通知通道 - 这是正确的吗?同样,我试图弄清楚如何创建类似于 Facebook Messenger 的“浮动前台聊天头气泡/视图”。是否需要 Notificationn 频道?
    • 是的,您需要通知通道才能在 API 26+ 中显示通知。前台服务需要 API 26+ 中的通知。
    • 您能否简要介绍一下从 API-26 及更高版本开始创建前台浮动聊天头的步骤?同样,这些库或示例都不再起作用了,所以我只需要知道如何调整它们,或者我必须添加什么。我将非常感激。
    • 我以前从来没有做过那个具体的事情。但是我发布的 githbub 链接将为您提供 ForegroundService 部分。
    • 是的,我查看了您发布的链接,但它似乎非常面向检索位置 - 虽然它实现了前台服务,但我认为它最终会变得相当不同/偏离我需要做什么..我对某些事情还是有点陌生​​,所以越少混乱越好,你知道我的意思哈哈..我不需要我的手,但同时,我有时会发现很难根据 IM 实际尝试做的事情从一个示例中区分什么是需要的,什么是不需要的。我开始对实现这一目标失去希望:/
    猜你喜欢
    • 2019-02-28
    • 2018-10-25
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2013-04-22
    • 2022-06-10
    • 2019-07-30
    • 2019-06-09
    相关资源
    最近更新 更多