使用GPS获取空位置(android)

时间:2012-11-10 14:55:37

标签: gps locationmanager

我正在写一个代码,它会通过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来说比较新!

1 个答案:

答案 0 :(得分: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);