繁体   English   中英

从requestLocationUpdates()从GPS查找位置不起作用

[英]finding location from requestLocationUpdates() from GPS not working

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

Google Maps使用用户的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);
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM