【发布时间】:2019-09-06 11:24:27
【问题描述】:
我需要启动我的应用服务前台。我的代码在 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));
}
【问题讨论】:
-
你如何开始这个
Service? -
@JeelVankhede
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)); } -
startForeground(1, builder.build());将此行放在onCreate()中的 if 条件之外。
标签: java android notifications foreground foreground-service