0

我正在编写一个代码,它将通过 GPS 获取手机的位置。但是我得到一个 NULL 位置,这是为什么呢?这是我的代码:

final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );


if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
                    Toast.makeText(context, "GPS not enabled", 1).show();
                    String provider = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

                    if(!provider.contains("gps")){ //if gps is disabled
                        final Intent poke = new Intent();
                        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                        poke.setData(Uri.parse("3")); 
                        context.sendBroadcast(poke);


                        LocationManager locationManager;
                        String ccontext = Context.LOCATION_SERVICE;
                        locationManager = (LocationManager)context.getSystemService(ccontext);


                        String provider1 = LocationManager.GPS_PROVIDER;
                        Location location = locationManager.getLastKnownLocation(provider1);
                        String XYZ = updateWithNewLocation(location);
                        Toast.makeText(context, XYZ, 1).show();


                }

                else Toast.makeText(context, "GPS is enabled", 1).show();




    }

这是 updatewithnewlocation 方法:

private String updateWithNewLocation(Location location) {
        // TODO Auto-generated method stub

        String latLongString;
        String myLocationString;
        if(location!=null){
            double lat = location.getLatitude();
            double longi = location.getLongitude();
            latLongString = "Latitude: "+lat+"  Longitude: "+longi;


        }
        else
        {
            latLongString = "Not found!";
        }

        return latLongString;
    }

基本上,我打开 GPS,然后尝试获取手机的当前位置 - 但为什么我得到一个空位置?

请帮忙,我对android比较陌生!

4

1 回答 1

0

可能是您的 GPS 存在未知问题。您还可以使用最佳提供商

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

  Criteria criteria = new Criteria();
  criteria.setAccuracy(Criteria.ACCURACY_FINE);
  String provider = lm.getBestProvider(criteria, true);
  Location mostRecentLocation = lm.getLastKnownLocation(provider);
于 2012-11-10T15:09:05.897 回答