Служба Foreground останавливается на некоторых мобильных устройствах, когда приложение уничтожено - PullRequest
0 голосов
/ 10 мая 2019

Служба Foreground останавливается на некоторых мобильных устройствах, когда приложение уничтожено, требуется запустить службу Foreground, даже если приложение уничтожено.

Манифест:

<service android:name=".services.LocationService" />

Вот как я запускаю и останавливаю службу:

private void startLocationUpdates() {
    if (!isMyServiceRunning(LocationService.class)) {

        Intent locationServiceIntent = new Intent(this, LocationService.class);
        locationServiceIntent.putExtra(StringConstants.LOCATION_UPDATES, true);

        startService(locationServiceIntent);
    }
}

private void stopLocationUpdates() {
    Intent locationServiceIntent = new Intent(this, LocationService.class);
    locationServiceIntent.putExtra(StringConstants.LOCATION_UPDATES, false);

    startService(locationServiceIntent);
}

Служба:

public class LocationService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "Service started");
    if (intent != null) {
      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(1, notification);

      } else {

        startService(new Intent(getApplicationContext(), MyForeGroundService.class));

    }
    }
    return START_STICKY;

}}

private NotificationCompat.Builder getNotificationBuilder(){
    return new NotificationCompat.Builder(this)
            .setContentIntent(MyApp.pendingIntent)
            .setContentText("setContentText")
            .setContentTitle(getString(R.string.app_name))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_black_24px))
            .setSmallIcon(R.drawable.ic_arrow_back_black_24px);
}

1 Ответ

0 голосов
/ 13 мая 2019

для устройств с ОС Oreo и выше есть ограничение на запуск службы, вы должны показывать уведомление для устройств с Oreo и выше, вам нужно сделать еще одну вещь вместо startService(), попробуйте использовать startForegroundService() для более информация, пожалуйста, пройдите официальный документ https://developer.android.com/about/versions/oreo/background

...