Question: I am using `LocationManager` to get a single location fix:

```
public class MyActivity extends Activity {
    private LocationManager lm;
    private ProgressDialog myDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, ll);
        myDialog = ProgressDialog.show(this, null , "Determining Your Location", true);
    }

    class MyLocationListener implements LocationListener {
        public void onLocationChanged(Location location) {
            if (location != null) {
                ...

                lm.removeUpdates(this);
                myDialog.dismiss();
            }
        }
    }
}

```

As this stands listening for a location could potentially go on forever if a location fix cannot be found. I want to add some robustness to my code by ceasing to listening for a location after 60 seconds, and displaying an error to the user to saying that their location could not be determined.

How can I do this?

Answer: 
One way would be to use a Handler and use postDelayed after 60 sec to stop the listener.

[Handler postDelayed](http://developer.android.com/reference/android/os/Handler.html#postDelayed%28java.lang.Runnable,%20long%29)
You can use Timer and TimerTask as well. When you create handler to utilise postDelayed, you should be careful of memory leak because the handler still refer your Activity or Service event after they are already finished. PostDelayed will be going to the message queue in the main thread. So, make your handler as static or use weak reference.

You need to consider following code to avoid the memory leak.

```
public class MyService extends Service {

   private static class MyHandler extends Handler {
      WeakReference<MyService> ref;

      public MyHandler(MyService r) {
         ref = = new WeakReference<MyService>(r);
      }

      public void handleMessage(Message msg) {

         MyService service = ref.get();
         if (servic==null) {
            return;
         }

         //Do something here
     }

   }

}

```