Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android system killed my service when I clear all recent app

I already using startforeground() at my Service, but Android keeps killing my Service when I clear all the recent apps.

Here's the code of my Service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("Text")
            .setTicker("Text")
            .setContentText("Text")
            .setSmallIcon(R.drawable.icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
            .build();

    startForeground(100, notification);

    return START_STICKY;
}

Is there something wrong I did with this code?

like image 678
zamroni hamim Avatar asked Mar 31 '16 05:03

zamroni hamim


People also ask

What does clearing recent apps do?

Android will manage it memory. If you clear your apps to often, it will only slow down your phone and make it work harder thus run out of battery faster. You only need to do that on older phone (before jelly bean) or if your phone has less than 2 gigs of RAM.

How to restart a service when the app is killed?

First, the easiest way to do what you're trying to do is to launch an Android Broadcast when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart after that. If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped.

How to fix random killing of background services on Android?

If you are still facing random killing of app’s background services, try doing the following change: Go to phone Settings. Tap on Battery. Select Battery optimization. From the top drop-down menu, change the type to All Apps. Select Notification History Log (or any app of your choice) from the list and change it to Don’t optimize.

Why does my Android system stop my service?

There are many situation where android system can stop your service like low battery, app is not in active state for a long time, device is in sleeping mode, power saving mode etc. I developed a trick or hack (you can say that) by using that no one can stop your service (Android System, Third Party apps, User).

How to stop apps from being killed automatically on Samsung devices?

Make the following changes in your Samsung device to stop apps from being killed automatically: Go to phone Settings. Open Device Care. Tap on Battery. Click on 3-vertical dots on the top right and select Settings. After disabling the above options, now click on Sleeping Apps.


2 Answers

A long running service needs the following to make it less likely to be terminated:

  1. Return START_STICKY from onStartCommand(). With this, system will re-start the service even if it has to be stopped for resources limitations.

  2. When the service is not bound to any UI component (e.g an Activity), The service must go in foreground mode by showing a foreground notification. Foreground services are less likely to be terminated by system.

  3. Set the attribute "stopWithTask"=false in corresponding <service> tag of manifest file.

Also, note that devices from some manufacturers will terminate services even with above properties due to customization:

  1. Custom task managers.
  2. Battery saving features that can prohibit non-system services.

Some application services do need to stay in background and have to be aggressively kept alive. Though this method is not recommended, but following steps can be done:

  1. Add triggers for service start : Such as Boot Complete, and Network Connected broadcasts.

  2. If service receives intents/broadcasts FLAG_RECEIVER_FOREGROUND in the intent.

  3. An extreme resort is to manually schedule a pending intent for service restart, with AlarmManager, when onTaskRemoved() is called.

Also, see:

  1. START_STICKY does not work on Android KitKat
like image 169
S.D. Avatar answered Oct 23 '22 09:10

S.D.


Android system can stop your service anytime when they want to stop to maintain the device performance or power consumption. There are many situation where android system can stop your service like low battery, app is not in active state for a long time, device is in sleeping mode, power saving mode etc.

I developed a trick or hack(you can say that) by using that no one can stop your service (Android System, Third Party apps, User).

Note: By using this your service will never stop and may drain your battery also.

Follow the steps below :-

1) Return START_STICKY in onStartCommand.

2) Then modify the onDestroy() and onTaskRemoved() method in your service as below:

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(getApplicationContext(), "Service Task destroyed", Toast.LENGTH_LONG).show();


    Intent myIntent = new Intent(getApplicationContext(), YourService.class);

    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);

    AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();

    calendar.setTimeInMillis(System.currentTimeMillis());

    calendar.add(Calendar.SECOND, 10);

    alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

  Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();

}




@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);


        Intent myIntent = new Intent(getApplicationContext(), YourService.class);

        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);

        AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(System.currentTimeMillis());

        calendar.add(Calendar.SECOND, 10);

        alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

        Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();


    }




@Override

    public int onStartCommand(Intent intent, int flags, int startId) {
     Toast.makeText(getApplicationContext(), "Service Starts", Toast.LENGTH_SHORT).show();
        return START_STICKY;
    }

Here i am setting an alarm every time whenever the service is stop (by android system or by user mannually) and using PendindIntent restart the service within 10 seconds every time.

like image 33
Ameer Faisal Avatar answered Oct 23 '22 09:10

Ameer Faisal