Reputation: 10437
I'm new to android, bear it with me.
I've a TimerTask for which I define run() inside the Service. Inside run(), I'm calling
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
LOCATION_UPDATES_MIN_TIME_MS, LOCATION_UPDATES_MIN_DISTANCE_M, gpsListener);
and it complains that can't create Handler, since I believe its a background thread. How do I solve it?
Edit: Code snippet
locationTask = new TimerTask() {
@Override
public void run() {
Log.d(Commands.TAG, "Running location Task");
myLocationProvider = new MyLocationProvider(locationManager, handler, MyService.this);
myLocationProvider.start();
myLocationProvider.stop();
}
};
and later its Scheduled as below:
locationTimer = new Timer();
locationTimer.schedule(locationTask, 10000, cmds.getAlertInterval()*60);
and when .start is called, requestLocationUpdates() fails
Upvotes: 6
Views: 3545
Reputation: 77722
You need to call requestLocationUpdates from within a thread with a looper, i.e. preferably the main thread. (requestLocationUpdates itself is quick and doesn't block, so there's no shame in doing so).
If your app is written in a way that simply prevents you from doing so, you can use a Handler. The documentation has an example that should be pretty much exactly what you need: http://developer.android.com/resources/articles/timed-ui-updates.html
Alternatively, you can create a Runnable with this instruction and call Activity.runOnUiThread()
on it.
Upvotes: 4