java - 我正在尝试在较旧的 API 版本上启动前台服务。使用 API 26+
问题描述
我需要启动我的应用服务前台。我的代码在 API 级别 26 和更高级别上运行良好,但不适用于较旧的 API 级别。在旧版本上,服务显示在正在运行的服务中,但不发送启动通知。我需要更改我的代码,为什么不起作用?
public void onCreate() {
super.onCreate();
messageIntent.setAction(getString(R.string.receiver_receive));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_DEFAULT)
.setOngoing(false).setSmallIcon(R.drawable.ic_launcher).setPriority(Notification.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_DEFAULT,
NOTIFICATION_CHANNEL_ID_DEFAULT, NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID_DEFAULT);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
startForeground(1, builder.build());
}
}
启动服务
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, SocketService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
ContextCompat.startForegroundService(this, new Intent(this, SocketService.class));
else
this.startService(new Intent(this, SocketService.class));
}
解决方案
方法ContextCompat.startForegroundService(...)
已经包含if
块:
public static void startForegroundService(@NonNull Context context, @NonNull Intent intent) {
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(intent);
} else {
// Pre-O behavior.
context.startService(intent);
}
}
只要打电话ContextCompat.startForegroundService(this, pushIntent)
。
你需要移到块startForeground
外if
:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
...
}
startForeground(1, builder.build());
此外,不要忘记调用notificationManagerCompat.notify(NOTIFICATION_ID, notification)
较旧的 API(如果通知未自动显示)。NOTIFICATION_ID
必须不为零!!!
推荐阅读
- javascript - 将 props 传递给子组件的最佳实践
- php - 使用 PHPMailer 将 dompdf 文件作为附件附加,而无需事先将文件保存到磁盘中
- php - 为什么 AJAX 在 WordPress 函数中运行两次
- java - 如何在调用父构造函数之前覆盖子类中的父类属性?
- jquery - jQuery多次调用click
- android - 需要让我的启动画面适合所有设备吗?
- excel - 在excel中从给定范围的行中查找常见行
- c# - Xamarin Forms CollectionView ScrollTo 在外部调用时
- python - 使用过去 24 小时的总和创建新列
- html - 当父级具有弹性方向时如何强制弹性项目不换行:列