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

3
我目前正在研究如何创建一个浮动的前景气泡聊天头服务。然而,我注意到我尝试使用的所有库都不适用于API-28。我认为这是由于Android文档此处提到的新限制所致。它基本上说明如果我调用显示前景内容的服务:我必须调用startForegroundService()而不是startService()。此外,它还指出:“系统创建服务后,应用程序有五秒钟时间调用服务的startForeground()方法来显示新服务的用户可见通知。” 我相信这可能是我无法使这些前台聊天头库正常工作的原因。请问能否提供一个示例,说明我应该如何实现这些?谢谢!
1个回答

6
@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));
    }

此外,这个项目是一个很好的基础,可以用来实现前台服务:

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


1
所以你的意思是,对于 API-26+,如果我要启动一个前台服务,我还需要创建一个通知渠道 - 是这样吗?再说一遍,我正在尝试弄清楚如何创建类似 Facebook Messenger 的“浮动前台聊天头气泡/视图”。这需要一个通知渠道吗? - Studio2bDesigns
您是否可以给我快速介绍一下如何在API-26及以上版本中创建前景浮动聊天头的步骤?再次强调,现有库和示例均已无法使用,因此我只需要知道如何进行调整或者我必须添加什么内容。非常感谢。 - Studio2bDesigns
是的,我看了你发的链接,但它似乎更偏向于检索位置 - 虽然它实现了前台服务,但我认为它与我需要做的事情会有很大不同.. 我对某些东西仍然比较新,所以越少混淆越好,你知道我的意思哈哈.. 我不需要别人帮我,但同时,有时候我很难区分从示例中需要和不需要的内容,基于我实际尝试做的事情。我开始对实现这个功能失去信心了 :/ - Studio2bDesigns
嘿Gavin,顺便问一下 - 你发布的那个代码片段,是不是应该放在一个单独的Activity中,然后根据用户的API版本启动前台服务?还是说这段代码应该放在服务本身中?我这么问是因为我注意到在意图中,你将ForegroundService.this作为源和目标都放了进去。能否简单地解释一下你这样做的原因呢?谢谢! - Studio2bDesigns
那么我应该从我的Activity中调用startForegroundService,就像我通常调用startService一样,然后在Service的onCreate中,我需要立即调用startForeground,对吗? 我唯一的问题是关于NotificationChannel之类的东西,因为我不熟悉使用它,也不确定为什么在我的用例中需要它,除了Android Oreo要求它之外。 你能否为我提供一个快速示例,告诉我如何在Activity和Service中使用可用代码来完成这个过程? - Studio2bDesigns
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接