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

Stu*_*gns 3 service android android-service foreground-service android-8.0-oreo

我目前正在研究如何创建浮动前景气泡聊天头服务。
但是,我注意到我尝试使用的所有库都无法在 API-28 上运行。我相信这是由于Android 文档中
提到的新限制造成的。 它本质上表明,如果我调用一个在前台显示内容的服务:我必须调用而不是. 此外,它还指出:“系统创建服务后,应用程序有五秒钟的时间来调用服务的方法来显示新服务的用户可见通知。” 我相信这可能是我无法让这些前台聊天库工作的原因。有人可以提供一个例子来说明我应该如何实现这些吗? 谢谢,麻烦您了!


startForegroundService()startService()


startForeground()




Gav*_*ght 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));
    }
Run Code Online (Sandbox Code Playgroud)

此外,该项目是实现 ForegroundService 的良好起点:

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