Q:

Failing to lock on to GPS after turning it on from settings

I am developing an app which asks users to enable the GPS if not on and then maps user location on Map. The problem I am facing is that after user enables the GPS from settings and presses back button, the Dialog box is shown saying "Location user location" but the app fails to get the longitude and latitude. Although if at this stage if I exit the app and start it again and access the same activity where the user location will be shown on map, then it works fine.
Following are the files used by me:
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// Flag for GPS status
boolean isGPSEnabled = false;

// Flag for network status
boolean isNetworkEnabled = false;

// Flag for GPS status
boolean canGetLocation = false;

Location location; // Location
double latitude; // Latitude
double longitude; // Longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

/******/

/****/

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // Getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // Getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // No network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {

                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // If GPS enabled, get latitude/longitude using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app.
 */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/Wi-Fi enabled
 *
 * @return boolean
 */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog.
 * On pressing the Settings button it will launch Settings Options.
 */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing the Settings button.
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // On pressing the cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

  @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

LocationActivity.java
public class LocationActivity extends Activity  {

Button btnGPSShowLocation;
Button btnSendAddress;
Button find_rick;
TextView tvAddress;
private ProgressDialog pDialog;
int progressBarStatus=0;
boolean shouldExecuteOnResume;
Handler progressBarHandler = new Handler();

AppLocationService appLocationService;

Button btnShowLocation;

// GPSTracker class
GPSTracker gps;

//Google maps implementation
GoogleMap googleMap;

private static final String TAG = LocationActivity.class.getSimpleName();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location_layout);

    shouldExecuteOnResume=false;
    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);
    pDialog.setMessage("Locating your location");
    pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pDialog.setProgress(0);
    pDialog.setMax(100);

    progressBarStatus = 0;

    createMapView();

    btnShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnSendAddress = (Button) findViewById(R.id.btnSendAddress);

            gps = new GPSTracker(LocationActivity.this);

            // Check if GPS enabled and if enabled  after popup then call same fn
            Log.d("OnCreate","OnCreate");
            MapMyCurrentLoction();

    btnShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            MapMyCurrentLoction();
        }
    });

    btnSendAddress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                String tag_string_req_send_data = "req_send";

                StringRequest strReq = new StringRequest(Request.Method.POST,
                        AppConfig.URL_AUTOWALA_DHUNDO, new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Autowala Response: " + response.toString());

                        try {
                            JSONObject jObj = new JSONObject(response);
                            boolean error = jObj.getBoolean("error");
                            if (!error) {
                                // User successfully stored in MySQL
                                // Now store the user in sqlite

                            } else {

                                // Error occurred in data sending. Get the error
                                // message
                                String errorMsg = jObj.getString("error_msg");
                                Toast.makeText(getApplicationContext(),
                                        errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Data sending Error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() {
                        // Posting params to register url
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("tag", "data_send");
                        params.put("latitude", Double.toString(gps.getLatitude()));
                        params.put("longitude", Double.toString(gps.getLongitude()));

                        return params;
                    }

                };

                // Adding request to request queue
                AppController.getInstance().addToRequestQueue(strReq, tag_string_req_send_data);

            }
        });

}
@Override
protected void onPause(){
    super.onPause();

}

@Override
protected void onResume(){
    super.onResume();
    if(shouldExecuteOnResume)
    {
        pDialog.show();

        new Thread(new Runnable() {
            public void run() {
                while (progressBarStatus < 100) {

                    progressBarStatus = getULocation();

                    try {
                        Thread.sleep(7000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            pDialog.setProgress(progressBarStatus);
                        }
                    });
                }

                if (progressBarStatus >= 100) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    pDialog.dismiss();
                }
            }
        }).start();
        //super.onResume();
    }
    else{

        shouldExecuteOnResume=true;

    }
    /*pDialog.setMessage("Locating your location");
    showDialog();*/

    /*while(gps.getLatitude()==0.0 && gps.getLongitude()==0.0)
    {

    }*/
    double latitude = gps.getLatitude();
    double longitude = gps.getLongitude();
    addMarker(latitude, longitude);
    //super.onResume();
}

private int getULocation()
{

    double latitude = gps.getLatitude();
    double longitude = gps.getLongitude();
    Location location;
    // The minimum distance to change Updates in meters
      final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
     final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
    boolean flag=gps.canGetLocation();
    LocationManager locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);
    location=locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    // Getting GPS status
    boolean isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    if(latitude > 0.0 && longitude > 0.0)
    {

        return 100;
    }
    else
    {

        return 0;
    }

}

private void createMapView(){
    /**
     * Catch the null pointer exception that
     * may be thrown when initialising the map
     */
    try {
        if(null == googleMap){
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
            googleMap.getUiSettings().setZoomGesturesEnabled(true);

            /**
             * If the map is still null after attempted initialisation,
             * show an error to the user
             */
            if(null == googleMap) {
                Toast.makeText(getApplicationContext(),
                        "Error creating map",Toast.LENGTH_SHORT).show();
            }
        }
    } catch (NullPointerException exception){
        Log.e("mapApp", exception.toString());
    }
}

/**
 * Adds a marker to the map
 */
private void addMarker(double lat,double lng){

    /** Make sure that the map has been initialised **/
    if(null != googleMap){
        googleMap.addMarker(new MarkerOptions()
                        .position(new LatLng(lat,lng))
                        .title("Your Location")
                        .draggable(true)
        );

        //zooming to my location
        float zoomLevel = 16.0F; //This goes up to 21
        LatLng coordinate = new LatLng(lat, lng);
        CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, zoomLevel);
        googleMap.animateCamera(yourLocation);
    }
}

private void MapMyCurrentLoction(){
    if (gps.canGetLocation()) {

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        addMarker(latitude,longitude);

                /*------- To get city name from coordinates -------- */
        String area = null;
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addressList = null;
        try {
            addressList = gcd.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (addressList != null && addressList.size() > 0) {
            Address address = addressList.get(0);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                sb.append(address.getAddressLine(i)).append("\n");
            }
            sb.append(address.getLocality()).append("\n");
            sb.append(address.getPostalCode()).append("\n");
            sb.append(address.getCountryName());
            area = sb.toString();
        }

        // \n is for new line
        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\n"+area, Toast.LENGTH_SHORT).show();
    }  else {
        // Can't get location.
        // GPS or network is not enabled.
        // Ask user to enable GPS/network in settings.
        gps.showSettingsAlert();

        //Again search and map my location after enabling gps

    }
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();

 }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}

When the app starts it's execution from onResume() method after user enables GPS from settings, even though isGPSEnabled returns true, I cannot get longitude or latitude and the dialog stays on screen until the app is closed. 
I am new to Android Development so many of this things are a bit confusing to me at this stage so it will be very useful if I can get a solution for the problem as soon I can.
EDIT
Problem:
I am using AsyncTask now for my purpose and I have taken out the getLocation() method out of the constructor. However now the dialog "Searching GPS.." is shown continuously because of the while loop used in doInBackground() method I guess.
Here is my class which uses AsyncTask
 private class InsertDataTask extends AsyncTask<Void, Void, Void> {

    private final ProgressDialog dialog = new ProgressDialog(LocationActivity.this);

    @Override
    protected Void doInBackground(Void... params) {
        Log.d("Before getLocation=",String.valueOf(gps._isGPSEnabled));
        gps.getLocation(LocationActivity.this);
        Log.d("After getLocation=", String.valueOf(gps._isGPSEnabled));

        while(gps.getLatitude()==0.0){
           //do nothing
        }

        return null;
    }

    // can use UI thread here
    protected void onPreExecute() {
        this.dialog.setMessage("Searching GPS...");
        this.dialog.show();
    }

    // can use UI thread here
    protected void onPostExecute(final Void unused) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }

        addMarker(gps.getLatitude(),gps.getLongitude());
    }
}

A:

Since ur calling getLocation() in constructor of GPS tracker class the method getLocation() gets executed only once (in this method only ur updating the status of the boolean canGetLocation) So when u execute the program without turning ON GPS it will update the status of canGetLocation to false and as ur saying when u turn it ON it will  never update the status because u are not calling the method getLocation from ur Activity anywhere(like on a button click). Instead ur just checking the boolean value which is always false until u exit ur App and come back(until u create a new object;i.e calling the constructor). So dont call the method getLocation from constructor instead call it on a Button click, so the boolean value will get updated as u turn ON the GPS. 

