我正在尝试在较旧的API版本上启动Foreground服务。在API 26+上工作

问题描述 投票:0回答:2

我需要启动我的应用服务前台。我的代码适用于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));
    }
java android notifications foreground foreground-service
2个回答
0
投票

在else语句中为apis启动服务。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    // only for newer versions
      Intent pushIntent = new Intent(this, ClassName.class);
      startForegroundService(pushIntent);
} else {
      Intent pushIntent = new Intent(this, ClassName.class);
      startService(pushIntent);
}

0
投票

为api低于26的设备编写代码,与if语句中的写入相同,不包括通知通道的部分,因为版本低于26的设备不支持通知通道

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // you had written code for device version greater than O
    } else {
       //You need to write code for device with lower version here
    }
© www.soinside.com 2019 - 2024. All rights reserved.