Restart the Service Even If App Is Force-Stopped and Keep Running Service in Background Even After Closing the App How

Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?

I am not sure which 'Task Manager' you are referring to as different ones would act differently, so I am basing my answer on the action when the user goes to Settings-->manage Applications and--> force stops the app the way android has given him.


Assuming that your service is running as part of the process and if the user force-stops your process, you are prevented from ever running the service again until the user manually launches you.This is especially valid from 3.0 and above version ( check for yours). It also seems logical when you think that there is an app which keeps a service started all the time and is annoying the user in some way. So when the user orders a hit ( :) force-stops) on the app, it should not restart the service to continue bugging the user.

For instance, Imagine what would happen if you could create apps which just ate at your processor time by holding a wake lock, and you couldn't kill them. This would be horrible and a huge security disaster.

So, you will not be able to restart your service by any means until the user launches one of your activities.

Also you cannot disable the force-stop button AFAIK. You should take the viewpoint that nothing on the device is yours to control besides your app and (to a limited extent) the resources to which you're granted access.

Finnally, even the gtalk app will bend to your will if you desire to force stop. It will start only when you use Gtalk or other apps which use the gtalk service such as PUSH Gmail ( for phones where gtalk isnt a part of firmware). Also take a look at Android C2DM here:

https://stackoverflow.com/a/11238779/1218762

Restart service after force stop

Updated :

Restart service after force stop

Answer : Sorry you can't restart it until the user manually launches application.

Assuming that your service is running as part of the process and if the user force-stops your process, you are prevented from ever running the service again until the user manually launches you.This is especially valid from 3.0 and above version ( check for yours). It also seems logical when you think that there is an app which keeps a service started all the time and is annoying the user in some way. So when the user orders a hit ( :) force-stops) on the app, it should not restart the service to continue bugging the user.

For instance, Imagine what would happen if you could create apps which just ate at your processor time by holding a wake lock, and you couldn't kill them. This would be horrible and a huge security disaster.

So, you will not be able to restart your service by any means until the user launches one of your activities.

Also you cannot disable the force-stop button AFAIK. You should take the viewpoint that nothing on the device is yours to control besides your app and (to a limited extent) the resources to which you're granted access.

Finnally, even the gtalk app will bend to your will if you desire to force stop. It will start only when you use Gtalk or other apps which use the gtalk service such as PUSH Gmail ( for phones where gtalk isnt a part of firmware).

Reference Link

Solution :

https://stackoverflow.com/a/11238779/1218762

How to keep a service running in background even after user quits the app?

Right from developer.android.com

A service is a component that runs in the background to perform
long-running operations or to perform work for remote processes. A
service does not provide a user interface. For example, a service
might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking
user interaction with an activity. Another component, such as an
activity, can start the service and let it run or bind to it in order
to interact with it. A service is implemented as a subclass of Service
and you can learn more about it in the Services developer guide.

So, as long as you create a service, and the user exits your app it will still run. Just like the example above.

This should give you all the information you need:
https://developer.android.com/guide/components/services.html

How to restart service after the app is killed from recent tasks

Override onTaskRemoved() in your service and use alarm manager to start the service again. Below is code from our app that does the same and works fine:

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

Log.d(TAG, "TASK REMOVED");

PendingIntent service = PendingIntent.getService(
getApplicationContext(),
1001,
new Intent(getApplicationContext(), MyService.class),
PendingIntent.FLAG_ONE_SHOT);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
}

As you may want to send location periodically even in the case if the service gets killed on low memory (or for any reason), I suggest you to handle the uncaughtException to restart it after N seconds. This is how we have done in our app that works perfectly:

private Thread.UncaughtExceptionHandler defaultUEH;
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {

@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.d(TAG, "Uncaught exception start!");
ex.printStackTrace();

//Same as done in onTaskRemoved()
PendingIntent service = PendingIntent.getService(
getApplicationContext(),
1001,
new Intent(getApplicationContext(), MyService.class),
PendingIntent.FLAG_ONE_SHOT);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
System.exit(2);
}
};

Note: I THINK and I remember I verified it on Kitkat that START_STICKY does not work on Kitkat and higher API levels. Please verify this for yourself.

MORE:
As you do loc sending periodically, you may have to consider the deep sleep mode. To get things work in deep sleep, use WakefulBroadcastReceiver combined with AlarmManager. Take a look at my other post How to use http in deep sleep mode.

UPDATE:
This solution does not work (in fact need not to work) if user "FORCE STOP" the application from Settings. This is good in fact as restarting the service is not a good way if user himself wants to stop application. So, it is fine.

Cannot keep android service alive after app is closed

Here is an example of foreground service that I use and that works, it remains active when the app is closed. Of course, it also must be started, and for that task the app must be running at a first glance, or a receiver of a boot event must be set, but this is another story.

public class MyService extends Service {
static final int NOTIFICATION_ID = 543;

public static boolean isServiceRunning = false;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
startServiceWithNotification();
}
else stopMyService();
return START_STICKY;
}

// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
isServiceRunning = false;
super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}

void startServiceWithNotification() {
if (isServiceRunning) return;
isServiceRunning = true;

Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
notificationIntent.setAction(C.ACTION_MAIN); // A string containing the action name
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);

Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.my_string))
.setSmallIcon(R.drawable.my_icon)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(contentPendingIntent)
.setOngoing(true)
// .setDeleteIntent(contentPendingIntent) // if needed
.build();
notification.flags = notification.flags | Notification.FLAG_NO_CLEAR; // NO_CLEAR makes the notification stay when the user performs a "delete all" command
startForeground(NOTIFICATION_ID, notification);
}

void stopMyService() {
stopForeground(true);
stopSelf();
isServiceRunning = false;
}
}

Then I run it with

    Intent startIntent = new Intent(getApplicationContext(), MyService.class);
startIntent.setAction(C.ACTION_START_SERVICE);
startService(startIntent);

Please note the two constants used as Actions, these are Strings that must start with the package name.



Related Topics



Leave a reply



Submit