0

I am using Timer and TimerTask in my Service and I am scheduling GPS to check periodically using this method @ Service - onCreate()

  scheduleAllGPST.scheduleAtFixedRate(new AllGPSTimer(), 0, 
                                                everyInterval); 

Code Snippet From my Service Class:

//class inside service class
class AllGPSTimer extends TimerTask {
   public void run() {
     if (!canGetLocation) stopLocationRequest();
     else requestLocation();
}
}
// Service class method
public void requestLocation() {
  try {
    locListener = new mylocationlistener();
    locationManager.requestLocationUpdates(provider, 0, 0, locListener);// Error happens at this line 
   }
  catch (Exception e) {
    e.printStackTrace();
  }
}
public void stopLocationRequest() {
 try {
    locationManager.removeUpdates(locListener);// And also it happens at this line 
 }
 catch (Exception e) {
    e.printStackTrace();
 }
}

I am getting this error:

Error :
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
 at android.os.Handler.<init>(Handler.java:121)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:139)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:137)
at android.location.LocationManager._requestLocationUpdates(LocationManager.java:708)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:630)
at com.mobile.sales.GPSService.requestLocation(GPSService.java:146)
at com.mobile.sales.GPSService$AllGPSTimer.run(GPSService.java:140)
at java.util.Timer$TimerImpl.run(Timer.java:289)

From the Error, I am guessing this requestLocationUpdates() and removeUpdates() can only be used from the Main thread of the Service class, not from the spawned thread of the main thread. Am I guessing it correctly?

So is there any method like runOnUiThread(runnable) in Activity class for the Service class?

Kindly any one help with I should handle location API methods and the spawned thread of the timer task? Also let me know if I am guessing it wrong .

Thank you!

pb2q
  • 58,613
  • 19
  • 146
  • 147
Pradeepraj
  • 423
  • 1
  • 8
  • 15
  • Look at this question http://stackoverflow.com/questions/3589963/locationmanager-requestlocationupdates-and-timertask-in-android – Kurovsky Jun 01 '12 at 09:23
  • @southerton : I saw the entire thing and source codes also So is that mean we cant use Timer while using locationApis ??? can you brief if there is any way ??? – Pradeepraj Jun 01 '12 at 10:13
  • hi @ Pradeepraj you notmalled we should not call any any hardware checking controls inside the thread. we should use Handler for that. following link will help you . http://developer.android.com/reference/android/os/Handler.html – itsrajesh4uguys Jun 01 '12 at 11:48
  • @Rajesh : thanks rajesh thats useful .. But i have tried KeyguardManager inside the Timer its working fine .. But for location its not working .. As Southerton commented LocationManager internally uses Looper and Handler So i am checking code snippets to handle the location manager in such a way – Pradeepraj Jun 01 '12 at 14:00

1 Answers1

0

public class GpsManager {

public GpsManager()
{
    // TODO Auto-generated constructor stub
}

LocationManager lm;
LocationListener ll;

public void Start(Context context)
{
    lm = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);


    isactive = true;



    handler=new Handler(){

        @Override
        public void handleMessage(Message msg)
        {

            if(isactive)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
            super.handleMessage(msg);
        }
    };
    ll = new MyLocationListener(context, lm,handler);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

Handler handler;
public boolean isactive;

public void Stop()
{
    lm.removeUpdates(ll);
    isactive = false;
}

class MyLocationListener implements LocationListener
{

    Context _con;
    LocationManager _lm;

    Handler _handler;
    public MyLocationListener(Context con, LocationManager lm,Handler h)
    {
        _lm = lm;
        _con = con;
        _handler=handler;
    }

    @Override
    public void onLocationChanged(Location location)
    {
        if (location != null)
        {

            Toast.makeText(
                    _con,
                    "lon = " + location.getLongitude() + ". lat = "
                            + location.getLatitude(), Toast.LENGTH_SHORT)
                    .show();
            lm.removeUpdates(this);
            Thread th=new Thread(new Runnable()
            {

                @Override
                public void run()
                {
                    Message msg=Message.obtain();
                    _handler.sendMessageDelayed(msg,1000);

                }
            });
            th.run();
        }

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {

        Toast.makeText(_con, "status change " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderEnabled(String provider)
    {

        Toast.makeText(_con, "provider enable " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String provider)
    {

        Toast.makeText(_con, "provider disable " + provider,
                Toast.LENGTH_SHORT).show();
    }

}

}