2012-05-23 84 views
0

我正在開發android應用程序來獲取我當前的經度和緯度從GPS。 我有下面的代碼無法獲取經度和緯度在android

public class setting extends Activity { 

TextView longval; 
TextView latval; 

@Override 
public void onCreate(Bundle savedInstanceState){ 
/** Called when the activity is first created. */ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.setting); 

    longval = (TextView)findViewById(R.id.longitudefield); 
    latval = (TextView)findViewById(R.id.latitudefield); 

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

//Location lastLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER); 
LocationListener locationListener = new myLocationListener(); 

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 
} 
class myLocationListener implements LocationListener{ 

    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     if(location != null){ 
      double longitude = location.getLongitude(); 
      double latitude = location.getLatitude(); 
      //Toast.makeText(getApplicationContext(), Double.toString(longitude), Toast.LENGTH_SHORT).show(); 
      longval.setText(Double.toString(longitude)); 
      latval.setText(Double.toString(latitude)); 
     } 
    } 

    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

    } 

} 

我不知道,當我把它放到我的手機(Galaxy Nexus的)。我在手機頂部的欄上看到一個GPS圖標。但是,文本字段未更新以顯示我當前的經度和緯度。我想問問這是我的代碼還是我的手機?我只是在沒有移動數據的情況下開啓wifi。看來onLocationChanged沒有被調用。

謝謝大家!

+0

提供[SSCE](http://sscce.org/)是一個開始。因爲它「看起來onLocationChanged沒有被調用」,你應該檢查它。 – keyser

+0

發佈你的logcat。那裏有明顯的錯誤? –

+0

我剛剛使用模擬器來修復這兩個值,並且它們在模擬器中正確顯示。但是,我無法在我的移動設備上執行此操作。 – user1311794

回答

4

它很難得到使用GPS的房間/公寓裏面的Lat,Long。代替LocationManager.GPS_PROVIDER使用LocationManager.NETWORK_PROVIDER ..它將解決您的問題。

+0

我想問如何更改爲代碼NETWORK_PROVIDER。只需更改locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);到locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener); }? } – user1311794

+0

是的...如果你使用getLastKnownLocation()方法,他們也使用NETWORK_PROVIDER .. –

0

您的代碼是正確的。將它安裝到您的設備上後,請將您當前的位置至少改爲10米。我們將從您當前的房間移動到距離至少10米的另一個房間。我希望您能得到您的輸出。 ..