2013-08-06 11 views
0

我的應用程序只需要知道用戶的國家,我的應用程序不關心用戶移動的位置。在Android中獲取用戶經度和緯度的最簡單方法是什麼?即使不使用監聽器?

我想知道的全部是: 當用戶啓動應用程序時,應用程序會將用戶的大致位置(緯度和經度)發送到服務器。

這是我的錯誤代碼。我嘗試發送一個字符串到getlocation函數,我希望它可以返回原始字符串並添加經度和緯度信息。

private String getlocation (String url){ 
    LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE)); 
    if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
     Log.v("print","enable to locate"); 
    } else { 
     Log.v("print","fail to locate"); 
    } 
    Location location = status.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
    if(location!=null){ 
     Log.v("print","[email protected]@"); 
     Double longitude = location.getLongitude(); 
     String loc=Double.toString(longitude); 
     url=url+loc; 
    } 
    else{ 
     Log.v("print","location return null"); 
    } 
    return url; 
} 

我用network_provider,它總是打印「啓用定位」,然後打印「位置返回NULL」

那麼,什麼是錯我的代碼,我的位置總是返回null。 我使用AVD manerger,我也嘗試GPS_PROVIDER。我使用Emulator控件在位置控制上發送Decimal。它也行不通。

那麼也設定網絡和GPS許可。

非常感謝您的幫助!

+0

沒有ü檢查logcat的,如果它是要求權限被添加到清單中? –

回答

1

我通過下面的代碼得到的位置,但啓用了「使用無線網絡」的設置,即(通過設置 - 定位服務 - 使用無線網絡)

public void getCurrentLocation() { 

    LocationManager locationManager; 
    String bestProvider; 

    // Get the location manager 
      locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

      Criteria criteria = new Criteria(); 
      bestProvider = locationManager.getBestProvider(criteria, false); 

      Location location = locationManager.getLastKnownLocation(bestProvider); 
      Log.e(TAG, "Latitude: "+location.getLatitude()+" , Longitude: "+location.getLongitude()); 
} 
+0

對不起〜你的意思是設置定位服務 - 在我的AVD手機上使用無線網絡?我選擇GPS和Wi-Fi和移動網絡,但它不起作用。 順便說一句,locationManager是否需要用Asynctask編寫? 或者只是在MainActivity中寫入很好? –

+0

我用過你的代碼,當我的應用程序「不幸關閉」時location.getLatitude()。 –

+0

它在我的平板電腦101上工作。星系。 使用 <使用權限android:name =「android.permission.ACCESS_FINE_LOCATION」/> –

相關問題