Android 从“设置”打开GPS后无法锁定GPS

Android 从“设置”打开GPS后无法锁定GPS,android,gps,Android,Gps,我正在开发一个应用程序,要求用户启用GPS(如果不启用),然后将用户位置映射到地图上。我面临的问题是,当用户从设置中启用GPS并按下后退按钮后,对话框显示“位置用户位置”,但应用程序无法获取经度和纬度。虽然在这一阶段,如果我退出应用程序并再次启动它,并访问用户位置将显示在地图上的相同活动,那么它可以正常工作 以下是我使用的文件: GPSTracker.java public class GPSTracker extends Service implements LocationListener

我正在开发一个应用程序,要求用户启用GPS(如果不启用),然后将用户位置映射到地图上。我面临的问题是,当用户从设置中启用GPS并按下后退按钮后,对话框显示“位置用户位置”,但应用程序无法获取经度和纬度。虽然在这一阶段,如果我退出应用程序并再次启动它,并访问用户位置将显示在地图上的相同活动,那么它可以正常工作

以下是我使用的文件: 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;
    }
}
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();
    }


}
LocationActivity.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;
    }
}
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();
    }


}
公共类LocationActivity扩展活动{
按钮BTNGPSS定位;
按钮btnSendAddress;
按钮找到里克;
文本视图地址;
私人对话;
int progressBarStatus=0;
布尔值应执行恢复;
Handler progressBarHandler=新处理程序();
AppLocationService AppLocationService;
按钮位置;
//GPSTracker类
全球定位系统;
//谷歌地图的实现
谷歌地图谷歌地图;
私有静态最终字符串标记=LocationActivity.class.getSimpleName();
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.location\u布局);
shouldExecuteOnResume=false;
//进度对话框
pDialog=新建进度对话框(此对话框);
pDialog.setCancelable(假);
setMessage(“定位您的位置”);
pDialog.setProgressStyle(ProgressDialog.STYLE_微调器);
pDialog.setProgress(0);
pDialog.setMax(100);
progressBarStatus=0;
createMapView();
btnShowLocation=(按钮)findViewById(R.id.btnGPSShowLocation);
btnSendAddress=(按钮)findViewById(R.id.btnSendAddress);
gps=新的GP斯特拉克(LocationActivity.this);
//检查GPS是否启用,如果在弹出后启用,则调用相同的fn
Log.d(“OnCreate”、“OnCreate”);
mapmyCurrentLocation();
btnShowLocation.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
mapmyCurrentLocation();
}
});
btnSendAddress.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
String tag_String_req_send_data=“req_send”;
StringRequest strReq=新的StringRequest(Request.Method.POST,
AppConfig.URL\u AUTOWALA\u DHUNDO,new Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
Log.d(标记“Autowala响应:”+Response.toString());
试一试{
JSONObject jObj=新的JSONObject(响应);
布尔错误=jObj.getBoolean(“错误”);
如果(!错误){
//用户成功存储在MySQL中
//现在将用户存储在sqlite中
}否则{
//发送数据时出错。获取错误信息
//信息
String errorMsg=jObj.getString(“error_msg”);
Toast.makeText(getApplicationContext(),
errorMsg,Toast.LENGTH_LONG).show();
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(标记,“数据发送错误:+Error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
@凌驾
受保护的映射getParams(){
//发布参数以注册url
Map params=新的HashMap();
参数put(“标记”、“数据发送”);
参数put(“latitude”,Double.toString(gps.getLatitude());
参数put(“经度”,Double.toString(gps.getLongitude());
返回参数;
}
};
//将请求添加到请求队列
AppController.getInstance().addToRequestQueue(streq、标记字符串请求发送数据);
}
});
}
@凌驾
受保护的void onPause(){
super.onPause();
}
@凌驾
受保护的void onResume(){
super.onResume();
如果(应执行恢复)
{
pDialog.show();
新线程(newrunnable()){
公开募捐{
而(状态<100){
progressBarStatus=getULocation();
试一试{
睡眠(7000);
}捕捉(中断异常e){
e、 printStackTrace();
}
progressBarHandler.post(新的Runnable(){
公开募捐{
pDialog.setProgress(progressBarStatus);
}
});
}
如果(progressBarStatus>=100){
试一试{
睡眠(1000);
}捕捉(中断异常e){
e、 printStackTrace();
}
pDialog.disclose();
}
}
}).start();
//super.onResume();
}
否则{
shouldExecuteOnResume=true;
}
/*setMessage(“定位您的位置”);
showDialog()*/
/*而(gps.getLatitude()==0.0&