Hi
I need to create a service that runs a piece of code in new thread after (let us say) 10 mins. How can I do that? I have service ready but I don't seem to understand how (if ) to call timer from within thread. can any one help?
After some (more) searching on StackOverFlow I found something that helps me
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
// code here what ever is required
handler.postDelayed(this, 10*600);
}
};
handler.postDelayed(r, 10*600);
The easiest way is to create new Handler. You get new thread and you can execute code defined in Runnable handleMyAction after 10 minutes:
mMessageHandler.postDelayed(handleMyAction, 1000*600);
You should not rely on timer. You service may be killed during these 10 minutes and timer will be destroyed. The reliable way is to use AlarmManager Frequently updating widgets (more frequently than what updatePeriodMillis allows)
Related
I am working on an application which requires it to go online every x minutes and check for some new data. To prevent heavy network and data usage the task should run at fixed rate, but what is the best approach to use for this kind of solution ? A Handler or a Timer object?
There are some disadvantages of using Timer
It creates only single thread to execute the tasks and if a task
takes too long to run, other tasks suffer.
It does not handle exceptions thrown by tasks and thread just terminates, which affects
other scheduled tasks and they are never run.
Whereas on Other hand, ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case
scheduleAtFixedRate(...)
scheduleWithFixedDelay(..)
class LongRunningTask implements Runnable {
#Override
public void run() {
System.out.println("Hello world");
}
}
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
long period = 100; // the period between successive executions
exec.scheduleAtFixedRate(new LongRunningTask (), 0, duration, TimeUnit.MICROSECONDS);
long delay = 100; //the delay between the termination of one execution and the commencement of the next
exec.scheduleWithFixedDelay(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
And to Cancel the Executor use this - ScheduledFuture
// schedule long running task in 2 minutes:
ScheduledFuture scheduleFuture = exec.scheduleAtFixedRate(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
... ...
// At some point in the future, if you want to cancel scheduled task:
scheduleFuture.cancel(true);
You should use a Service and an AlarmReceiver
Like This
That's what they're for. If you use a Timer or any other mechanism in your Activity and you set your data to update every "few minutes" there's a good chance the user will not be in your app and Android may very well clean it up, leaving your app *not updating. The Alarm will stay on till the device is turned off.
if you are looking for a good performance and less battery consume, you should consider an Alarm manager integrated with broadcast Reciever that will call a service in X time and let it do the work then turn it off again.
However, using timer or handler you need to let your service run in background at all times. unless, you want it to get data while the application is running therefore you dont need a service.
if your choice is whether handler or timer, then go with timer because it is more simpler and can do the job in better performance. handlers usually used to update the UI using Runnable or Messeges.
Maybe Alarm Manager, timer, handler or ScheduledThreadPoolExecutor.
Take a look at this:
Scheduling recurring task in Android
It depends on whether updates will occur while the user is not in the app (will the checks halt as soon as the user leaves to send an SMS, for example, or should polling continue?) can the check run on the UI thread then spawn the loading from a service or AsyncTask or other thread? Maybe none of that matters...
If you don't need to update anything while the user is not viewing the app, go with timer. Service would be an overkill. Here is a sample code to achieve this:
final Runnable updateRunnable = new Runnable() {
public void run() {
// Fetch the date here in an async task
}
};
final Handler myHandler = new Handler();
private Timer myTimer;
private void updateUI() {
myHandler.post(updateRunnable);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ... other things here
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
updateUI(); // Here you can update the UI as well
}
}, 0, 10000); // 10000 is in miliseconds, this executes every 10 seconds
// ... more other things here
}
Alarm manager or handler. If you use handler and postDelayed, your process doesn't have to stay active all the time.
In fact using Handler is officially recommended over Timer or TimerTask: http://android-developers.blogspot.ru/2007/11/stitch-in-time.html
What I want is 5 minutes after I open the application do a specific work.
I am not sure what I suppose to do.Should I create an AsyncTask in onCreate method of my main activity or a thread? Or should i do something completely different?
This may help: http://developer.android.com/reference/android/app/AlarmManager.html
Your question is a combined question asking how (way) to perform a task as well as how to schedule it.
Decide what is the task you want to perform. If its a long running task, use either AsyncTask or IntentService
To schedule the task you can either use Hander postDelayed, Timer or AlarmManager. My pref. would be a one-time AlarmManager - Once registered, even if you app is not running, the callback will be triggered.
You could use a Handler :
new Handler().postDelayed(new Runnable() { public void run() {
//your delayed action here, on UI Thread if needed
}
}, 1000 * 60 * 5 );
Regards,
Stéphane
I try to develop a simple timer beeper, that peep hourly. For the timing I use a Service and handler, here the example:
void onStart(...){
handler.postDelayed(timerRunnable, ONE_HOUR);
}
private Runnable timerRunnable = new Runnable() {
#Override
public void run() {
...beep
handler.postDelayed(timerRunnable, ONE_HOUR);
}
};
but run() method will be fired nondeterministic, I think it is dependent from the current device usage.
I have try the same scenario with TimerTask and with 'manualy' Thread implementation, but with the same nondeterministic result.
You'll probably have better luck using the AlarmManager for such a long delay. Handler is best for ticks and timeouts while your app is in the foreground.
http://developer.android.com/reference/android/app/AlarmManager.html
Android is not a real-time operating system. All postDelayed() guarantees is that it will be at least the number of milliseconds specified. Beyond that will be dependent primarily on what the main application thread is doing (if you are tying it up, it cannot process the Runnable), and secondarily on what else is going on the device (services run with background priority and therefore get less CPU time than does the foreground).
I've been working with Android for just a couple of weeks now and have some troubles with Services.
I have a background service running which checks every minute or so if a scheduled action needs to be executed. Second use is to store some user data and make them available for my activities. There are two issues:
The service gets binded by my main application but it seems that once I quit the main app, the service gets destroyed too. Why is that and what can I do against it?
The service doesn't run forever but seems to get stopped at a random point.
I understand why Android kills my service and so on and I also tried to use the AlarmManager instead of using a Timer in the service. These approaches somehow work, but they are just not versatile and dynamic enough.
So how can I have both an regular schedule check and some kind of data-sharing the right Android-like way?
You need to read about
local service
and remote service
You can use following link to see difference or goto http://developer.android.com/guide/topics/fundamentals.html link to read about fundamental component of android.
http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-for_04.html
http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-part-9.html
You can run a thread using TimerTask and Timer to schedule your task at regular interval
I was using following code to show result on UI.
Handler handler = new Handler();
Timer t;
TimerTask timeTask;
protected void usingTimerTask() {
t = new Timer();
timeTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
btn1.setText("Hi");
}
});
}};
t.scheduleAtFixedRate(timeTask, new Date(), 1000);
}
I am trying to write an android app that acquires a GPS signal at a fix time interval, for example every 1 minute. Since the requestLocationUpdate function does not exactly implement that, I tried to use task to accomplished it.
public class getGPS extends TimerTask{
public void run(){
System.out.println("Running a GPS task");
locHandler = new locationUpdateHandler();
myManager.requestLocationUpdates(provider, 60000, 0, locHandler);
}
}
public void LoadCoords(){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new getGPS(), 0, 60000);
}
However, from what I've seen, requestLocationUpdates would run fine if I put it inside LoadCoords(), but would not run if I put it inside the TimerTask (ie no green icon on the task bar to show that GPS is looking for a fix).
Can anyone please suggest an alternative approach or pseudo-code, or correct my mistake if there is one ? Thank you in advance.
As the doc says: The calling thread must be a Looper thread such as the main thread of the calling Activity. In other words you should call myManager.requestLocationUpdates(provider, 60000, 0, locHandler); from a main UI app thread. In your case that does not work from the TimerTask, because TimerTasks are being executed by Timer on a separate thread.
Check the Painless Threading article to find out your best fitting solution.