我想在Android应用程序中找到我当前位置的纬度和经度.当我用手机稳定时,我只需要它.
我的代码是:
LocationManager locationManager;
locationManager = (LocationManager)getSystemService
(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation
(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,0,0,(LocationListener) this);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location) {
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
String latLongString;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
Run Code Online (Sandbox Code Playgroud)
在模拟器上运行后,我总是找到"找不到位置".为什么会这样?
Joh*_*ick 15
public class GPSmap extends Activity {
GeoPoint geoPoint;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager locManager;
setContentView(R.layout.main);
locManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
500.0f, locationListener);
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location) {
TextView myLocationText = (TextView) findViewById(R.id.text);
String latLongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" + latLongString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider,int status,Bundle extras){}
};
}
Run Code Online (Sandbox Code Playgroud)
如果您将使用此代码,您将得到答案.
GPS 无线电不会一直保持开启状态,因为它会严重耗尽电池电量。当您打电话时getLastKnownLocation(),收音机可能已关闭。
您需要requestLocationUpdates()先完成您的工作,然后等待向您的LocationListener. 此后的任何时间(直到您removeUpdates())都getLastKnownLocation()应该返回一个非null值。
| 归档时间: |
|
| 查看次数: |
39521 次 |
| 最近记录: |