Reputation: 13537
We have developed an Android Application which involves a service in the background. To implement this background service we have used IntentService
. We want the application to poll the server every 60 seconds
. So in the IntentService
, the server is polled in a while loop. At the end of the while loop we have used Thread.sleep(60000)
so that the next iteration starts only after 60 seconds.
But in the Logcat
, I see that sometimes it takes the application more than 5 minutes to wake up (come out of that sleep and start the next iteration). It is never 1 minute
as we want it to be.
What is the reason for this? Should background Services be implemented in a different way?
Problem2
Android kills this background process (intent service) after sometime. Can't exactly say when. But sometimes its hours and sometimes days before the background service gets killed. I would appreciate it if you would tell me the reason for this. Because Services are not meant to be killed. They are meant to run in background as long as we want it to.
Code :
@Override
protected void onHandleIntent(Intent intent) {
boolean temp=true;
while(temp==true) {
try {
//connect to the server
//get the data and store it in the sqlite data base
}
catch(Exception e) {
Log.v("Exception", "in while loop : "+e.toString());
}
//Sleep for 60 seconds
Log.v("Sleeping", "Sleeping");
Thread.sleep(60000);
Log.v("Woke up", "Woke up");
//After this a value is extracted from a table
final Cursor cur=db.query("run_in_bg", null, null, null, null, null, null);
cur.moveToLast();
String present_value=cur.getString(0);
if(present_value==null) {
//Do nothing, let the while loop continue
}
else if( present_value.equals("false") || present_value.equals("False") ) {
//break out of the while loop
db.close();
temp=false;
Log.v("run_in_bg", "false");
Log.v("run_in_bg", "exiting while loop");
break;
}
}
}
But whenever the service is killed, it happens when the the process is asleep. The last log reads - Sleeping : Sleeping
. Why does the service gets killed?
Upvotes: 39
Views: 62657
Reputation: 2554
The main problem is that we cannot say
Services are not meant to be killed. They are meant to run in background as long as we want it to.
Basically, that is not true. System still can terminate the service in low memory and possibly other situations. There are 2 ways to overcome this:
onStartCommand()
and return START_STICKY
as the result. It will tell the system that even if it will want to kill your service due to low memory, it should re-create it as soon as memory will be back to normal.Upvotes: 82
Reputation: 196
You can try Jobscheduler implementation with JobService running in Background, which is recommended above Android O.
Upvotes: 0
Reputation: 11141
It could be probably for two reasons..
temp==true
Adding to it is threads, that is creating long delays
upto 6 seconds
.
In case, the system is working for a large database, creating long delays
between each query will add on the system memory.
When the memory usage for application become so huge that the system memory gets low
, system has to terminate the process
..
Solution for the Problem..
You could replace above with Alarm Manager
to revoke system services after a particular interval of time using Alarm Manager.
START_REDELIVER_INTENT
. It is to get your last working intent back after the application terminates. for its usage, study https://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENTUpvotes: 0
Reputation: 673
Android is pretty good about killing off long running services. I have found CommonsWare's WakefulIntentService useful in my application: https://github.com/commonsguy/cwac-wakeful
It allows you to specify a time interval as you are trying to do by sleeping.
Upvotes: 0
Reputation: 2817
For Problem 1, from vanilla Java, Thread.Sleep()
is guaranted to wake the thread after the timer has expired, but not exactly after it has expired, it may be later depending mainly of the statuses of other threads, priority, etc.; so if you sleep your thread one second, then it will sleep at least a second, but it may be 10 depending of a lot of factors, i'm not very versed in Android development, but i'm pretty sure it's the same situation.
For Problem 2, services can be killed when memory get low or manually by the user, so as others have pointed probably using AlarmManager to restart your service after a certain time will help you to have it running all the time.
Upvotes: 1
Reputation: 6323
Services get killed. Like app gets killed. It is Android philosophy that you can get killed at any time.
You should as other wrote not make the assumption that your backgroundservice runs forever.
But you can use a foreground service to drastically reduce the chance of getting killed/restarted. Note that this forces a notification which is always visible. For example music players, vpn applications and sportstracker use this API.
Upvotes: 2
Reputation: 1590
A better solution would be have an AlarmManager go off every 60 seconds. This AlarmManager then starts the service that polls the server, the service then starts a new AlarmManager, its a recursive solution that works quite well.
This solution will be more reliable as you dont have the threat of the Android OS killing your service, looming over you. As per API: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
In your UI/main activity etc, set this timer, to go off in 60 seconds:
long ct = System.currentTimeMillis(); //get current time
AlarmManager mgr=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent i= new Intent(getApplicationContext(), yourservice.class);
PendingIntent pi=PendingIntent.getService(getApplicationContext(), 0, i, 0);
mgr.set(AlarmManager.RTC_WAKEUP, ct + 60000 , pi); //60 seconds is 60000 milliseconds
In yourservice.class
you could have this, it checks the connection state, if its good it sets the timer to go off in another 60 seconds:
public class yourservice extends IntentService {
public yourservice() { //needs this constructor
super("server checker");
}
@Override
protected void onHandleIntent(Intent intent) {
WifiManager wificheck = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if(check for a certain condition your app needs etc){
//could check connection state here and stop if needed etc
stopSelf(); //stop service
}
else{ //poll the server again in 60 seconds
long ct = System.currentTimeMillis();
AlarmManager mgr=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent i= new Intent(getApplicationContext(), yourservice.class);
PendingIntent pi=PendingIntent.getService(getApplicationContext(), 0, i, 0);
mgr.set(AlarmManager.RTC_WAKEUP, ct + 60000 , pi);
stopSelf(); //stop service since its no longer needed and new alarm is set
}
}
}
Upvotes: 4
Reputation: 63955
IntentService
is not intended to keep running in a while
loop. The idea is to react to an Intent
, do some processing and stop the service once done.
That does not mean that it's not working and I can't tell you why you see such long delays but the cleaner solution is to use some external source to poke the service periodically. Besides vanilla Java methods you can also have a look at the AlarmManager
or a Handler
as mentioned in the AlarmManager
documentation.
The Handler
way would work like this
public class TriggerActivity extends Activity implements Handler.Callback {
// repeat task every 60 seconds
private static final long REPEAT_TIME = 60 * 1000;
// define a message id
private static final int MSG_REPEAT = 42;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler(this);
}
@Override
protected void onStart() {
super.onStart();
// start cycle immediately
mHandler.sendEmptyMessage(MSG_REPEAT);
}
@Override
protected void onStop() {
super.onStop();
// stop cycle
mHandler.removeMessages(MSG_REPEAT);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler = null;
}
@Override
public boolean handleMessage(Message msg) {
// enqueue next cycle
mHandler.sendEmptyMessageDelayed(MSG_REPEAT, REPEAT_TIME);
// then trigger something
triggerAction();
return true;
}
private void triggerAction() {
// trigger the service
Intent serviceIntent = new Intent(this, MyService.class);
serviceIntent.setAction("com.test.intent.OPTIONAL_ACTION");
startService(serviceIntent);
}
}
A simple Activity
(which could be extended to have that functionality in all your activities) that sends itself a Message
all the time while it is running (here between onStart
and onStop
)
Upvotes: 5
Reputation: 7329
Sound like you should be using a Service
instead of an IntentService
but if you want to use an IntentService
and have it run every 60 seconds you should use the AlarmManager
instead of just telling the Thread
to sleep.. IntentService
s want to stop, let it and have AlarmManager
wake it up when it should run again.
Upvotes: 0
Reputation: 48262
You could use ScheduledExecutorService designed specifically for such purpose.
Don't use Timers, as demonstrated in "Java Concurrency in Practice" they can be very inaccurate.
Upvotes: 6