W
W
web_dev2016-03-11 23:40:47
Android
web_dev, 2016-03-11 23:40:47

Always running service with no activity?

Hello, I tried several options, but none of them work.
Does someone know how to make such a service, or at least, so that it re-creates itself when an activity from the list is killed?
The service works, but as soon as I remove the activity from the stack, it stops working. Preferably starting with android 5(API 21).
Here's what I tried.
In service. Doesn't restart.

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartService = new Intent(this,
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                this, 0, restartService,
                0);

        AlarmManager alarmService = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmService.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 5 * 1000, restartServicePI);
//Этот вариант тоже не работает
//            getApplicationContext().startService(new Intent(getApplicationContext(), BackgroundService.class));
    }

The service (BroadcastReceiver ) doesn't work either.
@Override
    public void onDestroy() {
        super.onDestroy();
        sendBroadcast(new Intent("YouWillNeverKillMe"));
    }

public class BootBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context ctx, Intent intent) {
        Log.i("WTW", "ServeiceDestroy onReceive...");
        ctx.startService(new Intent(ctx.getApplicationContext(), BackgroundService.class));
    }
}

In the manifest also declared..
<receiver android:name=".BootBroadcast">
            <!--<intent-filter>-->
                <!--<action android:name="android.intent.action.BOOT_COMPLETED" />-->
            <!--</intent-filter>-->
            <intent-filter>
                <action android:name="YouWillNeverKillMe" >
                </action>
            </intent-filter>
        </receiver>

Or is it still impossible? Many write that it is.
Thanks for the hints.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2016-03-11
@web_dev

everything is possible
on habré there are 2 articles on how to make tenacious services

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question