从GPS中的requestLocationUpdates()查找位置无法正常工作

时间:2016-09-13 09:21:09

标签: android gps maps

我正在创建一个地图应用程序,它从GPS获取位置,我从requestLocationUpdates()查找位置,但我没有得到GPS提供商的任何响应,但是当我正在使用网络提供商我正在获取位置,任何人都可以在我错的地方帮忙,

我也是Android应用程序开发的新手,所以我会感谢任何优化我的代码的提示(使用更少的混乱更有效率),

这是我的代码:

public void trackLocation(){
    if (ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
        boolean flag;
        Boolean dlg;
        flag = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (flag) {
            Log.v("function", "onClick");
            myLocationListener = new MyLocationListener();
            dlg = true;
        } else {
            dlg = gpsDialog();
            progressBar.setVisibility(View.GONE);
        }

        Log.d("maps", "Requesting location updates");
        if(dlg) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
        }
    }
}

public class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Log.d("maps", "on location changed : "+location.getLatitude() + "---"+ location.getLongitude());
        locationManager.removeUpdates(myLocationListener);
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        Log.d("maps" , "Status Changed");
    }

    @Override
    public void onProviderEnabled(String s) {
        Log.d("maps" , "Provider Enabled");
    }

    @Override
    public void onProviderDisabled(String s) {
        Log.d("maps" , "Provider Disabled");
    }
}

public Boolean gpsDialog(){
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setMessage("Do you want to start GPS?")
            .setCancelable(false)
            .setTitle("GPS DISABLED")
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // finish the current activity
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            activity.startActivity(myIntent);
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // cancel the dialog box
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
    progressBar.setVisibility(View.GONE);
    return false;
}

3 个答案:

答案 0 :(得分:2)

Google地图使用用户lastKnownLocation作为位置,如果lastknownLocation未知,则需要时间通过不同的提供商GPSNetwork获取位置,以较容易的方式为准。我建议使用lastKnownLocation作为基本位置,并使用LocationListener更新它。它是处理位置最优化的方式。

       if (ActivityCompat.checkSelfPermission
                (this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                &&
                ActivityCompat.checkSelfPermission
                        (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 1);

        }
        else {

            // enable location buttons
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);

            // fetch last location if any from provider - GPS.
            final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            //if last known location is not available
            if (loc == null) {

                final LocationListener locationListener = new LocationListener() {
                    @Override
                    public void onLocationChanged(final Location location) {

                        // getting location of user
                        final double latitude = location.getLatitude();
                        final double longitude = location.getLongitude();
                        //do something with Lat and Lng
                    }

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

                    @Override
                    public void onProviderEnabled(String provider) {
                        //when user enables the GPS setting, this method is triggered.
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        //when no provider is available in this case GPS provider, trigger your gpsDialog here.
                    }
                };

                //update location every 10sec in 500m radius with both provider GPS and Network.

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 500, locationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
            }
            else {
                //do something with last known location.
                // getting location of user
                final double latitude = loc.getLatitude();
                final double longitude = loc.getLongitude();
            }
        }

许可处理:

     @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {

        case 1:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
                //do something
            }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

答案 1 :(得分:1)

您的代码是正确的。 GPS通常不会在大楼内提供任何信息,如果您尝试在外面测试应用程序,您将获得结果。

答案 2 :(得分:1)

firstly check gps_enabled return true or not.

LocationManager lm = (LocationManager) mCtx
                .getSystemService(Context.LOCATION_SERVICE);

gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

By this code you get accurate lat , long 


Location net_loc = null, gps_loc = null, finalLoc = null;

if (gps_enabled)
    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (gps_loc != null && net_loc != null) {

    if (gps_loc.getAccuracy() >= net_loc.getAccuracy())
        finalLoc = gps_loc;
    else
        finalLoc = net_loc;

        // I used this just to get an idea (if both avail, its upto you which you want to take as I taken location with more accuracy)

} else {

    if (gps_loc != null) {
        finalLoc = net_loc;
    } else if (net_loc != null) {
        finalLoc = gps_loc;
    }
}