[英]How to get current location in android?
我正在使用以下代碼獲取我當前的位置,沒有 GPS,但我想在祝酒詞中顯示坐標。 我試過這段代碼,但它顯示我的包名而不是坐標!
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
//makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Toast.makeText(getBaseContext(), "location is:"+locationListener, Toast.LENGTH_LONG).show();
}
您的onLocationChanged()
回調中只有位置。
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Toast.makeText(getBaseContext(), "location is:"+location, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
您正在嘗試敬酒 locationListener 對象。您必須創建一個 Location 位置; 烘烤時的對象和吐司 location.getLatitude() 和 location.getLongitude() 方法。
您當前的代碼在注冊 LocationListener 時祝酒,並在偵聽器上調用 Object.toString() ,它只返回偵聽器的類名。
您想將 Toast.makeText(... 行移動到 onLocationChanged 函數內部,並將文本更改為"location is:"+location
,或者可能"location is: "+location.getLatitude()+","+location.getLongitude()
。
此外,每次他獲得新位置時,此代碼將繼續制作 Toasts。 您可能希望使用 LocationManager.requestSingleUpdate 僅制作一個 toast,或者將 LocationManager.removeUpdates 放在 onDestroy 中,以便在活動完成時停止。
首先創建 FMLocationListener 類。
private static class FMLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
然后使用以下代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.