首页 > 解决方案 > 我正在尝试在较旧的 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));
    }

标签: javaandroidnotificationsforegroundforeground-service

解决方案


方法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)

你需要移到块startForegroundif

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    ...        
}
startForeground(1, builder.build());

此外,不要忘记调用notificationManagerCompat.notify(NOTIFICATION_ID, notification)较旧的 API(如果通知未自动显示)。NOTIFICATION_ID必须不为零!!!


推荐阅读