Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler inside a Thread run

Tags:

android

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

like image 739
Taranfx Avatar asked Aug 22 '10 18:08

Taranfx


Video Answer


1 Answers

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.

like image 130
EboMike Avatar answered Oct 21 '22 03:10

EboMike