tags:

views:

33

answers:

1

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

+1  A: 

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.

EboMike
I can't run it from main thread as it has to be a part of TimerTask (which is a thread), and when I surround it with Looper.prepare();requestLocationUpdates();Looper.loop();it would freeze at the last statementFor your alternative solution, Activity cannot be used since this is a Service and not a UI Thread.Any alternatives?
taranfx
In what thread did you create the Handler? Can you post a bit more of the code, and the error message?
EboMike