Я пытаюсь запустить службу Foreground на более старой версии API. Работа над API 26+ - PullRequest
0 голосов
/ 16 апреля 2019

Мне нужно запустить службу приложений на переднем плане.Мой код отлично работает с 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));
    }

Ответы [ 2 ]

0 голосов
/ 16 апреля 2019

Записать код для устройств с 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
    }
0 голосов
/ 16 апреля 2019

запустить сервис для нижеуказанного 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);
}
...