我目前正在研究如何创建一个 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/