从GPS的requestLocationUpdates()中获取位置信息不起作用

3
我正在创建一款地图应用程序,该应用程序从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个回答

3

谷歌地图使用用户的lastKnownLocation作为位置信息,如果lastKnownLocation未知,则需要通过不同提供者(如GPS网络)获取位置信息,这需要一些时间。我建议使用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);
    }
}

谢谢你的建议,但是正如我说的,之前我已经使用了lastknownlocation,但它并不总是准确的,我同意它速度快,但每次我都需要准确性。 - Deepak Joshi
@DeepakJoshi 这段代码是一年前的 Endomondo 版本,它是使用 LocationListener 进行位置过滤的最优化方式。如果您不想使用 lastKnownLocation,请删除我的代码中的 lastknowlocation 方法,它仍然可以正常工作。 - W4R10CK
1
谢谢,它起作用了。我写错了if语句来检查自身权限。 - Deepak Joshi

1

您的代码是正确的。通常情况下,GPS在室内不会提供任何信息,如果您试图在室外测试应用程序,则会得到结果。


1
在 onLocationChanged() 中,我将位置打印在日志中,但在 GPS 提供程序的情况下,它不显示任何内容,但在网络提供程序中,它会在日志中给出。 - Deepak Joshi

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

非常感谢你的帮助,非常感谢,但是我不想使用getLastKnownLocation()方法,因为它获取的是设备上最后一次已知的GPS定位。如果我关闭GPS然后从一个位置到另一个位置再打开GPS,它将在最初几次尝试中得到旧的位置坐标,而不是请求新的位置。我之前使用这个方法时就遇到了这个问题。我可以发送我的完整代码,但我觉得那可能没有太大用处。 - Deepak Joshi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接