GPS can't run inside TimerTask - android

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.

Related

Handler or a Timer for scheduling fixed rate tasks

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

How to stop Thread in Android?

I had a thread which executes a function in every 30 minutes, so I used a combination of handler and runnable thread ( like postdelayed,removemessages ).At that time I couldn’t find any way to stop thread.I tried hander. Removemessages() and hander.removeCallbacks(Runnable) but couldn’t help..
I will suggest you to use TimerTask instead of Thread. Here you can cancel & restart the TimerTask.
I suggest you to use alarmmanager. There is a problem with timertask.
Sometimes the service where the timertask is initiated might be destroyed. If the service is not running timertask will also become disable. It happen frequently when the device is in idle state. So the best solution is to use alarmmanager which trigger an alarm in every 30 minutes whether your device is in idle state or not. You only need to initiate the alarm when you first start the application and need to re-initiate when the device is rebooted. You can use a broadcast receiver to get message when your device is rebooted.
To stop a thread in java, you need to call thread.interrupt(); method.
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if(your condition to stop thread)
{
timer.cancel();
}else
{
\\ your code
}
}
}, 0, 1800000);
use timer inside....it will solve your problem

Call a specific action in certain time in Android

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

LocationManager in Service - need to stop if no fix in 1 minute

I have regular service that I start using alarms every 5 minutes.
Service Implements LocationListener to get GPS fix and save it into SqLite database.
I give service 1 minute to get best fix possible. If I get accuracy <20 before that - even better.
All that works fine. I also have code that checks if GPS disabled so I exit service.
What I want to do is: If there is no fix within 1 minute - I want to exit service. Currently since most logic (time checks, etc) is in onLocationChanged - I never have chance to do so because I never get location.
Is there timer or something like that I can use? I'm new to Java, example would be nice. I see it like this: On start I create timer with callback and in this callback function I will cleanup and shutdown. I'm not sure if there going to be any implications with possible onLocationChanged running?
Can I possibly disable timer as soon as I get onLocationChanged?
Use a android.os.Handler:
Handler timeoutHandler = new Handler();
timeoutHandler.postDelayed(new Runnable() {
public void run() {
stopSelf();
}
}, 60 * 1000);
You could schedule a timeout using Timer and TimerTask as follows...
Declare a global Timer object reference in your Service:
Timer timeout = null;
In onStartCommand(), instantiate this Timer and schedule a TimerTask to execute in one minute. Do this after you've registered for location updates from the desired provider:
timeout = new Timer();
timeout.schedule(timeoutTask, 60000);
Define timeoutTask somewhere in your Service class e.g:
private TimerTask timeoutTask = new TimerTask() {
public void run() {
// Handle timeouts here
}
}
If you get a callback via onLocationChanged() before the Timer expires, you'll want to stop timeoutTask from being executed, so inside onLocationChanged():
if(timeout != null) {
timeout.cancel()
}
Then just handle your location inside onLocationChanged() as normal, or call another method to do it, up to you.
There are probably better ways to do it, but this is straightforward and has worked for me on my project :) Hope it helps you too.
All the best,
Declan

Android: How to run thread in Service after timely intervals?

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)

Categories

Resources