На уровне API 26, Android ограничил доступ к фоновой службе.Вы можете решить эту проблему, запустив свой сервис в качестве переднего плана.
У меня была такая же проблема с моим единственным проектом, и я исправил ее, используя приведенный ниже код.
В YourService.class
private static final String NOTIFICATION_CHANNEL_ID_DEFAULT = "my_flow_notification_channel_default";
@Override
public void onCreate() {
super.onCreate();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_DEFAULT)
.setOngoing(false).setSmallIcon(R.drawable.ic_notification).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());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO:
return START_STICKY;
}
Для запуска службы
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
ContextCompat.startForegroundService(context, new Intent(context, YourService.class));
else
context.startService(new Intent(context, YourService.class));
Для остановки службы
stopService(new Intent(getActivity(), YourService.class));
В вашем AndroidManifest.xml
Добавьте это разрешение
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Добавьте это внутри тега.
<service
android:name=".service.YourService"
android:enabled="true"
android:exported="true" />
Надеюсь, что это поможет ..:)