Не удается сохранить работу службы в Android

Пробовал темы:

Не удается сохранить службу Android после приложение закрыто

Служба Android останавливается, когда приложение закрыто< /а>

Я пробовал это без успеха

Я хочу, чтобы IntentService работал в фоновом режиме, даже когда приложение убито. Но если я удалю свое приложение с экрана последних событий, моя служба остановится. Как я могу этого избежать? Другими словами, как я могу поддерживать работу службы, даже если мое приложение закрыто для недавних приложений?

Моя служба переднего плана:

public class ForegroundService extends Service {
private static final String LOG_TAG = "ForegroundService";
public static boolean IS_SERVICE_RUNNING = false;

private NotificationManagerCompat notificationManagerCompat;
final NotificationCompat.Builder playingChannelID = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID);


@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    notificationManagerCompat = NotificationManagerCompat.from(this);

    if (intent != null && intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
        showNotification();
    } else if (intent != null && intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
        MainActivity.exoPlayer.setPlayWhenReady(false);
        notificationManagerCompat.cancel(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE);
        stopSelf();
    }
    return START_STICKY;
}
private void showNotification() {
    createNotificationChannel();

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);
    Intent playIntent = new Intent(this, ForegroundService.class);
    playIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
    PendingIntent pplayIntent = PendingIntent.getService(this, 0,
            playIntent, 0);
    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.drawable.r);

    playingChannelID.setContentTitle("Service");
    playingChannelID.setContentText("Playing...");
    playingChannelID.setSmallIcon(R.drawable.Service);
    playingChannelID.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
    playingChannelID.setContentIntent(pendingIntent);
    playingChannelID.setOngoing(true);
    playingChannelID.addAction(android.R.drawable.ic_delete, "Turn Off",
                    pplayIntent).build();notificationManagerCompat.notify(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, playingChannelID.build());
}
@Override
public void onDestroy() {
    super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
    // Used only in case if services are bound (Bound Services).
    return null;
}

private void createNotificationChannel() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = Constants.NOTIFICATION_NAME;
        String description = Constants.NOTIFICATION_DESCRIPTION;
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel channel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
}

Мои константы:

public class Constants {
public static String NOTIFICATION_CHANNEL_ID = "NOTIFICATION_CHANNEL_ID_RADIO";
public static String NOTIFICATION_NAME = "RADIO_NOTIFICATION";
public static String NOTIFICATION_DESCRIPTION = "NOTIFICATION_DESCRIPTION";
public interface ACTION {
    public static String MAIN_ACTION = "com.marothiatechs.foregroundservice.action.main";
    public static String PLAY_ACTION = "com.marothiatechs.foregroundservice.action.play";
    public static String STARTFOREGROUND_ACTION = "com.marothiatechs.foregroundservice.action.startforeground";
    public static String STOPFOREGROUND_ACTION = "com.marothiatechs.foregroundservice.action.stopforeground";
}
public interface NOTIFICATION_ID {
    public static int FOREGROUND_SERVICE = 101;
}
}

Мои манифесты:

        <service android:name=".service.ForegroundService" >
        <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </service>

Я вижу, что служба работает, когда приложение открыто. Он все еще работает, когда я сворачиваю приложение с помощью кнопки «Домой». Он все еще работает, когда я закрываю приложение с помощью кнопки «Назад». Но это остановится, если я убью его, как указано выше. Как мне это решить?


person Son    schedule 07.10.2018    source источник


Ответы (1)


Если вам нужна служба переднего плана, вы должны вызвать startForeground(). Я рекомендую вам прочитать эту статью, если вы не хотите, чтобы ANR был включен Устройство Oreo и выше. Если вы тестируете свое приложение на устройствах Xiaomi, вам необходимо разрешить автозапуск приложения в настройках.

person Aleksandr Melnikov    schedule 07.10.2018