служба переднего плана не сохраняется, когда приложение закрывается из фонового трея

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

Код для отображения уведомления:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand executed");
    context = AppController.getInstance().getApplicationContext();
    if (intent.getAction().equals("com.truiton.foregroundservice.action.startforeground")) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction("com.truiton.foregroundservice.action.main");
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        Intent previousIntent = new Intent(this, ConnectivityCheckReceiver.class);
        previousIntent.setAction("com.truiton.foregroundservice.action.prev");
        PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                previousIntent, 0);

        Bitmap icon = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);

        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("Truiton Music Player")
                .setTicker("Truiton Music Player")
                .setContentText("My Music")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(
                        Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .addAction(android.R.drawable.ic_media_previous,
                        "Previous", ppreviousIntent)
                .build();
        startForeground(101,
                notification);
    }
    return START_STICKY;
}

person Vishakha Gahukar    schedule 08.03.2018    source источник
comment
Покажите нам соответствующий код   -  person fillobotto    schedule 08.03.2018
comment
@fillobotto Я отредактировал свой вопрос, добавив код.   -  person Vishakha Gahukar    schedule 08.03.2018
comment
Весь этот код должен быть помещен внутри onCreate метода обслуживания   -  person fillobotto    schedule 08.03.2018
comment
где написать код для отправки данных на сервер?   -  person Vishakha Gahukar    schedule 08.03.2018
comment
Вы должны использовать onCreate только для создания уведомлений и startForeground. Остальная логика вашего сервиса остается неизменной. Вы по-прежнему звоните в службу поддержки и уточняете намерение внутри onStartCommand   -  person fillobotto    schedule 08.03.2018
comment
Пробовал и это... но все же уведомление исчезает после закрытия приложения из области последних приложений.   -  person Vishakha Gahukar    schedule 08.03.2018
comment
onTaskRemoved() Службы в этом случае срабатывает метод. Может быть, вы могли бы использовать это, чтобы вернуть уведомление.   -  person Markus Kauppinen    schedule 08.03.2018
comment
есть ли что-нибудь, кроме службы startForeground, которая будет сохраняться, когда приложение будет удалено из списка последних приложений. Я даже пробовал firebasejobdispatcher, но из-за нестандартной ОС на некоторых устройствах, таких как Redmi, он ограничивает работу по расписанию.   -  person Vishakha Gahukar    schedule 08.03.2018
comment
@VishakhaGahukar ты решил это? Пожалуйста, поделитесь решением   -  person Shruti    schedule 12.10.2018
comment
@Shruti Смотрите мой ответ ниже   -  person Pierre    schedule 26.04.2019


Ответы (1)


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

Манифест Android:

<service android:directBootAware="true"
    android:enabled="true"
    android:exported="true"
    android:name=".ForegroundService1">
    . . .
</service>

Ваш класс обслуживания:

public class ForegroundService1 extends android.app.Service
{
    static final int foregroundID = 1234567;
    static final string channelID = "Sync notification";
    ...

    @override
    public int onStartCommand(Intent intent, int flags, int startId) {
    {
        Notification notification = new NotificationCompat.Builder(this, channelID)
                                                  .setContentTitle("Syncing ...")
                                                  .setContentText("Some more text")
                                                  .setSmallIcon(Resource.Drawable.my_notification)
                                                  .setOngoing(true)
                                                  .setAutoCancel(false)
                                                  .build();

        //If Build >= Android Oreo
        //Create notification channel for channelID
        //@see https://developer.android.com/training/notify-user/channels#CreateChannel

        startForeground(foregroundID, notification);

        //Create Handler on separate thread, run your sync inside runnable
        HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
        handlerThread.start();
        Looper looper = handlerThread.getLooper();
        Handler handler = new Handler(looper);
        handler.post(new Runnable() {
            @Override  
            public void run() {
                StartSync();
            }
        });

        return Service.START_STICKY;
    }

    private void StartSync()
    {
        //Your code here which runs for a long while..

        //After you are done, stop the service and foreground notification
        stopForeground(true);
        stopSelf();
    }
}

Начать

Intent i = new Intent(context, ForegroundService1.class);
android.support.v4.content.ContextCompat.StartForegroundService(context, i);
person Pierre    schedule 26.04.2019