从设置开启后无法锁定GPS

时间:2015-07-09 08:16:17

标签: android gps

我正在开发一个应用程序,要求用户启用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;
    }
}

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


}

当应用程序启动时,用户从设置启用GPS后,从onResume()方法执行,即使isGPSEnabled返回true,我也无法获得经度或纬度,并且对话框会一直停留在屏幕上,直到应用程序关闭。

我是Android开发人员的新手,所以在这个阶段我对这些事情有点困惑,所以如果我能尽快找到解决问题的方法,这将非常有用。

修改

问题: 我现在正在使用AsyncTask达到我的目的,我已经从构造函数中取出了 getLocation()方法。但是现在连续显示“搜索GPS ..”对话框,因为我猜想在doInBackground()方法中使用了while循环。 这是我的类使用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());
    }
}

1 个答案:

答案 0 :(得分:-1)

由于你在GPS跟踪器类的构造函数中调用 getLocation(),方法getLocation()只执行一次(在此方法中只更新boolean canGetLocation的状态)所以当你执行程序没有打开GPS它会将 canGetLocation的状态更新为false 并且当你打开它时它会说它永远不会更新状态,因为你没有在任何地方调用ur的方法getLocation(比如点击按钮)。相反,你只需检查一直是假的布尔值,直到你退出你的应用程序并返回(直到你创建一个新对象;即调用构造函数)。所以不要从构造函数调用方法getLocation而是在Button click 上调用它,因此当你打开GPS时,布尔值会更新。