As a requirement in Android OS phone, I am developing an app which will clean up a particular folder in a specified interval of time, say every 30 minutes.
I can run a service and clean up the folder every 30 mins. I have few questions over this,
1.Service has onStartCommand, which will be executed when the service starts, can I call a function here which has a Handler which runs every 30 minutes? Example
public int onStartCommand(Intent intent, int flags, int startId){
cleanUpData();
return START_REDELIVER_INTENT;
}
public void cleanUpData()
{
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// call the function again
cleanUpData();
}
}, "30 mins");
}
This code iterates the cleanUpData every 30 mins.
a. Is this correct?
b. Will this hamper the performance?
c. Should I use a separate thread as mentioned in numerous tutorials?
d. Should I use a service after-all? Or is there any other method?
AlarmManager provides the scheduled repeated alarms, but this does not work when the phone is in sleep mode. I do not want to wake up the screen as it does not require any human interaction. Can I ignore AlarmManager? Or does AlarmManager has functionality to run the code even when the phone is in sleep mode and phone wake up is false?
Please suggest. Thanks in advance!
you should use a separate thread for cleaning up the folder.I will not suggest you to use handler inside a service as it runs in the same process as app so a long running operation can make it unresponsive,instead of this use intentservice as it runs on its own thread.
And for the device sleep problem fire an broadcast receiver and acquire custom wake up lock in this broadcast receiver and then invoke your service from here.
I get the current location in my app using requestLocationUpdates but in case it takes too long to detect I use a timer to cancel the operation.
For your information I tell you I do all this process in a WakefulBroadcastReceiver so the device should NOT sleep until either a position is received or the time out happens. Once one of those happens I call to completeWakefulIntent to let the device sleep again.
Everything works great but sometimes the timer never finishes and no location is got, either. I guess my process is maybe killed or destroyed by the system.
So, is there a way to ensure the timer to execute after an amount of time?
Any help would be appreciated
Check AlarmManager.
Schedule a non repeating alarm once the location finding activity is fired.
This alarm in turn fires your killer activity that cancels the location finding activity, after an appropriate amount of time
Or use Handler. Something like:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// do something
// this executes after 2000 milliseconds
}
}, 2000);
When it runs on the main thread you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed).
Also if this BroadcastReceiver was launched through a <receiver> tag, then the object is no longer alive after returning from onReceive(). This means you should not perform any operations that return a result to you asynchronously.
Please see the documentation for BroadcastReceiver
Cheers!
Use Timer.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//This will execute afteer every 1 Minute
}
}, 0, 60000);
I am using AlarmManager of Android and scheduling a repeating alarm using elapsed_time_wakeup for every minute. This alarm fires of a service.
Service does its work (pinging the server(Facebook server in my case) to get data). Next I call onDestroy() of the service. So every minute Service starts -> Does work -> onDestroy()
Is the best way to do this in android?
Do you really need new service every minute? I think you want to start single service. That service does each minute check on server and reports success or error somehow? You want simple always running service with periodic action, not periodic service starting. In this case, starting new service would consume maybe more resources than check itself.
Just make sure service stays running. That might be case until you call stopSelf() from it and starting activity does not stop it also. You may want to run it as
private ping() {
// periodic action here.
scheduleNext();
}
private scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 60000);
}
int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return STICKY;
}
You might want periodic check only on Wifi connection or connection present. And maybe to stop checking when you already know about problem and are solving it. You may want to use startForeground() from Service to start some activity to control it and display results.
My Activity starts a service by calling startservice(). To simplify my problem lets say the service will be a counter, and the counter will be increased in every 10 sec.
Timer t_counter;
int counter = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
t_counter = new Timer();
t_counter.schedule(new TimerTask() {
#Override
public void run() {
counter++;
Log.d("counter: ",Integer.toString(counter));
}}, 0, 10000);
return Service.START_STICKY;
}
When the phone is being charged, (or in debug mode - since I can see the the Logcat) the service works as expected. In around every 10 sec Logcat shows the debug info, whenever the app is in background or not. But when I have unplugged the phone, the service stops running after a while. Event when the app (Activity which started the service) is active. Note that service not destroyed, just put on hold, or something like this.
Because when I plug in the mobile again, the timer continues and the value of the counter is being increased from the value where I just unplugged the phone. So if the service has been destroyed then value would have been zero again. (also I debugging the lifecycle of the service, and cannot see onStartCOmmand(), onDestroy() would have been called )
I have searched solutions for it, but I think I have not het the right answer for this behavior.
I know that I should use AlarmManager instead of Timer. Or it would also work if I put the service foreground by startForeground(), or maybe separate process would solve this problem. But I would like to know why my solution is working with charging. Also where can I find infos about this "idle" state of a service. (not executing timer schedules, but not destroyed) Thanks!
You need to hold lock if your service has to be running in the background
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl =
pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
// when you done
wl.release();
Better way is to use AlarmManager because keep the service running all the time will drain the battery and waste the system resources.
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?
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:
If you are implementing the service, override 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.
If you are not sure 1st approach will work - you'll have to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html . That is a system service, which will execute actions when you'll tell, for example periodically. That will ensure that if your service will be terminated, or even the whole process will die(for example with force close) - it will be 100% restarted by AlarmManager.
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.
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)
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
}
}
}
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.
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.
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.. IntentServices want to stop, let it and have AlarmManager wake it up when it should run again.
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.
It could be probably for two reasons..
Either the while loop is creating an issue, it is making the handler to work until 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.
Also for getting intent back after the system recovers the application from termination, you should use 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_INTENT
You can try Jobscheduler implementation with JobService running in Background, which is recommended above Android O.