I have an app that runs as a web server. The app has a service that is START_STICKY I want this service to run the web server all the time (option is given to user in a notification to stop it).
Problem is that the server is restarted (loosing settings etc) when i swipe my app closed. It stays there fine but logcat shows that it is restarting.
I can re- open my app and bind to the new service, this works fine. Although swipe closing again has the same effect.
I need this to NOT restart.
Standard service code
private WebServerService mService;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder binder) {
WebServerService.MyBinder b = (WebServerService.MyBinder) binder;
mService = b.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
public serviceStart() {
mIntent = new Intent(mContext.getApplicationContext(), WebServerService.class);
mContext.startService(mIntent);
mContext.bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
}
Service on start
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, START_STICKY, startId);
Log.d("SERVICE","Started");
return START_STICKY;
}
Short answer: you can't. Every Android app can be killed by the system or by the user when the system claims memory or the user swipes out the app from the recent apps list. This is an Android design and all apps must adhere to it. The only (small) improvement you can have is setting the service as a Foreground service:
where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
Use startForeground()
The drawback is that you'll have to provide a notification.
Like Mimmo said: You can't. The system can indeed kill apps/services if low on memory. Also users can do this. Either with the force close button in app settings or swiping the app. Swipe to close is like the force stop. The app/service DOES NOT RESTART when closing an app like this. That is just how the system works. Try it yourself, download advance task killer and kill Facebook for example. If you restart advance task killer a few seconds later, you will see Facebook is running again. Now open Facebook and use the swipe function to kill it. Now start the task killer again. You will see Facebook is not running anymore. Again, that is how the system works.
Setting the service as a Foreground service is not going to help either.
Will the tag android:process="anyname" on your manifest be useful? It makes the service run on a different process of your app.
http://developer.android.com/guide/topics/manifest/service-element.html#proc
As appointed by others it still can be terminated by the system if running low on memory but it won't terminate by closing your app. Hope it helps.
Related
I have a location service which I want to run at all times when the app is in the foreground, or in the background, but to stop when the app is closed (removed from the app tray)
My solution has been to start the service using START_NOT_STICKY and this seems to work, but I'm concerned by what the service documentation says about this command
START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
So it seems that Android may kill off services when memory is low, and if using START_NOT_STICKY the service will not be restarted.
I tried using START_STICKY but this keeps the service running even after the app is closed.
What can I do to keep the service running at all times while the app is in the foreground or background, and stop after being closed, but without worrying about Android terminating it while the app is running?
Code here if it matters:
#Override
public int onStartCommand(Intent intent, int flags, int startId){
if (intent != null) {
extras = intent.getExtras();
// takes the messenger object and makes it local so when the messagereceiver sends an intent here, it won't overwrite the extras object
// and get rid of the messenger. Otherwise, getting an update from the notification controls would null out the messenger object
if (intent.hasExtra("MESSENGER")) {
Timber.e("MESSENGER ");
messenger = (Messenger) extras.get("MESSENGER");
}
}
return START_NOT_STICKY;
}
What can I do to keep the service running at all times while the app is in the foreground or background, and stop after being closed, but without worrying about Android terminating it while the app is running?
I'm not sure what "app tray" you're referring to or what exactly you mean by "closed" (Android apps are not things that are "closed", per se.
But, from your description, I'd think you want to do something like:
Start your Service when the user starts your app and bind to while the activity is in the foreground
If your activity is paused (or stopped), unbind from the service and start a foreground notification to keep the service alive and the user aware that it's still running
Instead of trying to detect when the app is "closed", which you can't really do, attach a "cancel" action to the foreground notification so the user can cancel it whenever they want
If that doesn't solve your issue, please elaborate on your use case and why you want to do this. I or others may be able to provide more / better / alternate suggestions with more specifics about what you're actually ultimately trying to achieve.
Hope that helps!
I have an app with one activity and one service. If I kill the activity while the service is running it gets killed too. It is very important for me that the service doesn't get killed. How to make that when the system kills (or I kill it by clearing the "Recent apps" list) the activity the service still remains active until it finishes its job? Thanks in advance!
You can try returning START_STICKY from onStartCommand in your Service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
It is very important for me that the service doesn't get killed
Your processes can be killed at any time, for any reason, based on user activity (recent tasks list, a third-party task manager, "Force Stop" in Settings, etc.) or based on OS needs (system RAM is getting low). You cannot prevent this.
You can take some steps to minimize the odds of the OS deciding on its own to terminate your process, such as using startForeground() on the service, but this does block the user from doing what the user wants with your app's process.
I'm displaying a window from that service so if the service stops then the window disappears.
Presumably, the user wants your window to disappear if the user is explicitly getting rid of your app via the recent tasks list, a task manager, etc. You are certainly welcome to advise users in your documentation of any negative effects that this will have.
You are also welcome to experiment with having that service be in a separate process. My understanding is that this will not help with the recent-tasks list on Android 4.4, though it might on earlier versions of Android. Whether this helps with third-party task managers probably depends on the manager, and this should not help with "Force Stop" from settings. It also means that you will have to deal with IPC, increased system RAM consumption while your main and service processes are both running, etc.
Are you running a bound service? If so, then the system will kill it when the last client activity disconnects (terminates). Here's the blurb from the reference page:
When the last client unbinds from the service, the system destroys the
service (unless the service was also started by startService()).
Here is my Service
public class SService extends Service {
public void onCreate() {
super.onCreate();
someTask();
}
public int onStartCommand(Intent intent, int flags, int startId) {
someTask();
return START_STICKY;
}
public IBinder onBind(Intent intent) {
return null;
}
After force stop of app (Settings->Application->Force Stop App) my Service doesn't run. How to solve it?
As per the Android document
Starting from Android 3.1, the system's package manager keeps track of applications that
are in a stopped state and provides a means of controlling their launch from background
processes and other applications.
Note that an application's stopped state is not the same as an Activity's stopped
state. The system manages those two stopped states separately.
Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all broadcast intents. It
does this to prevent broadcasts from background services from inadvertently or unnecessarily
launching components of stoppped applications. A background service or application can
override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES flag to broadcast intents
that should be allowed to activate stopped applications.
On Force stop of app, Android just kill the process ID. No warnings, callbacks are given to service/activities. As per the Android document, When the app is killed there are chances that it calls onPause().
When I tried in my app, even onPause() was not called.
I think the only way is use to that intent flag and send it from another app as suggested by Chris.
Are you sure that the service isn't restarting? The START_STICKY you put in the return should do the trick some time. It takes some time till the system restart it, you can put a log and wait to make sure it's getting restarted.
I am referring to android design considerations: AsyncTask vs Service (IntentService?)
According to the discussion, AsyncTask does not suit, because it is tightly "bound" to your Activity
So, I launch a Thread (I assume AsyncTask and Thread belong to same category), have an infinity running loop in it and did the following testing.
I quit my application, by keeping pressing on back soft key, till I saw home screen. Thread is still running.
I kill my application, by going to Manage apps -> App -> Force stop. Thread is stopped.
So, I expect after I change from Thread to Service, my Service will keep alive even after I quit or kill my app.
Intent intent = new Intent(this, SyncWithCloudService.class);
startService(intent);
public class SyncWithCloudService extends IntentService {
public SyncWithCloudService() {
super("SyncWithCloudService");
}
#Override
protected void onHandleIntent(Intent intent) {
int i = 0;
while (true) {
Log.i("CHEOK", "Service i is " + (i++));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Log.i("CHEOK", "", ex);
}
}
}
}
// Doesn't matter whether I use "android:process" or not.
<service
android:name="com.xxx.xml.SyncWithCloudService"
android:process=".my_process" >
</service>
However, my finding is that,
I quit my application, by keeping pressing on back soft key, till I saw home screen. Service is still running.
I kill my application, by going to Manage apps -> App -> Force stop. Service is stopped.
It seems that the behaviour of Service and Thread are the same. So, why I should use Service instead of Thread? Is there anything I had missed out? I thought my Service suppose to keep running, even after I kill my app?
Nope. Service will stop running when you kill your application. When you kill your application all components of it are killed (activities, services, etc.).
In general the behaviour of Thread and Service are similar. However, If you start a Thread from an Activity and then shutdown the activity (ie: quit your application), eventually Android will notice that your process has no active components in it (since Android doesn't recognize your Thread as an active component) and it will just kill your process, thereby killing the thread.
However, if you have a Service running, then Android will notice that you have a service running and not kill it so readily. However, it is still possible that Android will kill your service process if it isn't "in use".
Actually there are different kinds of services you can implement. Use a Service instead of IntentService. There you need to look at START_STICKY , START_NOT_STICKY and START_REDELIVER_INTENT you can keep your service running in background even if your activity dies. Android services
You are using startService(). The Service will run until it's code is done, or until Android decides it should be killed. Look up on bound services. On your Activity.onDestroy() you should call unbindService().
In your IntentService you can override onStartCommand() returning START_REDELIVER_INTENT
Then if killed, your service will be restarted automatically by the system after some time with the same Intent.
Be sure to call the super implementation on onStartCommand() like this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
return START_REDELIVER_INTENT;
}
You can invoke setIntentRedelivery(true) in the constructor of the IntentService
I have a service that is defined as:
public class SleepAccelerometerService extends Service implements SensorEventListener
Essentially, I am making an app that monitors accelerometer activity for various reasons while the user sleeps with his or her phone/device on the bed. This is a long-running service that MUST NOT be killed during the night. Depending on how many background apps and periodic processes occur during the night, android sometimes kills off my process, thereby ending my service. Example:
10-04 03:27:41.673: INFO/ActivityManager(1269): Process com.androsz.electricsleep (pid 16223) has died.
10-04 03:27:41.681: INFO/WindowManager(1269): WIN DEATH: Window{45509f98 com.androsz.electricsleep/com.androsz.electricsleep.ui.SleepActivity paused=false}
I do not want to force the user to have 'SleepActivity' or some other activity in my app as the foreground. I can't have my service run periodically, because it is constantly intercepting onSensorChanged.
Any tips? source code is here: http://code.google.com/p/electricsleep/
For Android 2.0 or later you can use the startForeground() method to start your Service in the foreground.
The documentation says the following:
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
The is primarily intended for when killing the service would be disruptive to the user, e.g. killing a music player service would stop music playing.
You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section.
When you bind your Service to Activity with BIND_AUTO_CREATE your service is being killed just after your Activity is Destroyed and unbound. It does not depend on how you've implemented your Services unBind method it will be still killed.
The other way is to start your Service with startService method from your Activity. This way even if your Activity is destroyed your service won't be destroyed or even paused but you have to pause/destroy it by yourself with stopSelf/stopService when appropriate.
As Dave already pointed out, you could run your Service with foreground priority. But this practice should only be used when it's absolutely necessary, i.e. when it would cause a bad user experience if the Service got killed by Android. This is what the "foreground" really means: Your app is somehow in the foreground and the user would notice it immediately if it's killed (e.g. because it played a song or a video).
In most cases, requesting foreground priority for your Service is contraproductive!
Why is that? When Android decides to kill a Service, it does so because it's short of resources (usually RAM). Based on the different priority classes, Android decides which running processes, and this included services, to terminate in order to free resources. This is a healthy process that you want to happen so that the user has a smooth experience. If you request foreground priority, without a good reason, just to keep your service from being killed, it will most likely cause a bad user experience. Or can you guarantee that your service stays within a minimal resource consumption and has no memory leaks?1
Android provides sticky services to mark services that should be restarted after some grace period if they got killed. This restart usually happens within a few seconds.
Image you want to write an XMPP client for Android. Should you request foreground priority for the Service which contains your XMPP connection? Definitely no, there is absolutely no reason to do so. But you want to use START_STICKY as return flag for your service's onStartCommand method. So that your service is stopped when there is resource pressure and restarted once the situation is back to normal.
1: I am pretty sure that many Android apps have memory leaks. It something the casual (desktop) programmer doesn't care that much about.
I had a similar issue. On some devices after a while Android kills my service and even startForeground() does not help. And my customer does not like this issue. My solution is to use AlarmManager class to make sure that the service is running when it's necessary. I use AlarmManager to create a kind of watchdog timer. It checks from time to time if the service should be running and restart it.
Also I use SharedPreferences to keep the flag whether the service should be running.
Creating/dismissing my watchdog timer:
void setServiceWatchdogTimer(boolean set, int timeout)
{
Intent intent;
PendingIntent alarmIntent;
intent = new Intent(); // forms and creates appropriate Intent and pass it to AlarmManager
intent.setAction(ACTION_WATCHDOG_OF_SERVICE);
intent.setClass(this, WatchDogServiceReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
if(set)
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeout, alarmIntent);
else
am.cancel(alarmIntent);
}
Receiving and processing the intent from the watchdog timer:
/** this class processes the intent and
* checks whether the service should be running
*/
public static class WatchDogServiceReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(ACTION_WATCHDOG_OF_SERVICE))
{
// check your flag and
// restart your service if it's necessary
setServiceWatchdogTimer(true, 60000*5); // restart the watchdogtimer
}
}
}
Indeed I use WakefulBroadcastReceiver instead of BroadcastReceiver. I gave you the code with BroadcastReceiver just to simplify it.
http://developer.android.com/reference/android/content/Context.html#BIND_ABOVE_CLIENT
public static final int BIND_ABOVE_CLIENT -- Added in API level 14
Flag for bindService(Intent, ServiceConnection, int): indicates that the client application binding to this service considers the service to be more important than the app itself. When set, the platform will try to have the out of memory killer kill the app before it kills the service it is bound to, though this is not guaranteed to be the case.
Other flags of the same group are: BIND_ADJUST_WITH_ACTIVITY, BIND_AUTO_CREATE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_WAIVE_PRIORITY.
Note that the meaning of BIND_AUTO_CREATE has changed in ICS, and
old applications that don't specify BIND_AUTO_CREATE will automatically have the flags BIND_WAIVE_PRIORITY and BIND_ADJUST_WITH_ACTIVITY set for them.
Keep your service footprint small, this reduces the probability of Android closing your application. You can't prevent it from being killed because if you could then people could easily create persistent spyware
I'm working on an app and face issue of killing my service by on app kill. I researched on google and found that I have to make it foreground. following is the code:
public class UpdateLocationAndPrayerTimes extends Service {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForground();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForground() {
LocationChangeDetector locationChangeDetector = new LocationChangeDetector(context);
locationChangeDetector.getLatAndLong();
Notification notification = new NotificationCompat.Builder(this)
.setOngoing(false)
.setSmallIcon(android.R.color.transparent)
//.setSmallIcon(R.drawable.picture)
.build();
startForeground(101, notification);
}
}
hops that it may helps!!!!