2012-11-10 107 views
0

我正在寫一個代碼,它將通過GPS獲取手機的位置。不過,我得到一個空的位置,爲什麼呢?這裏是我的代碼:使用GPS獲取空位置(android)

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比較陌生!

+0

也許是因爲用戶強行關掉了GPS? –

回答

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); 
+0

現在我不需要定義MyLocationListerner類嗎?我會在那裏定義什麼? – Saturnian

+0

對不起,只是忽略MyLocationListerner() –