我想获取当前位置的纬度和经度。我使用了LocationManager,但它显示的位置为null,纬度和经度显示为0.0。我在清单和GPS连接中使用了所需的权限。
代码:
LocationdemoActivity.java :
public class LocationdemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(
getApplicationContext(),
"loc:" + MyLocationListener.location + "latitude "
+ MyLocationListener.latitude + "longitude "
+ MyLocationListener.longitude, 5000).show();
}
});
}
}
MyLocationListener.java :
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
public static Location location;
@Override
public void onLocationChanged(Location loc)
{
location = loc;
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
protected boolean isRouteDisplayed() {
return false;
}
}
清单中的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
有什么问题?
答案 0 :(得分:0)
尝试做这样的事情
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener);
location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(getApplicationContext(),
"loc:" + location + "latitude "
+ location.latitude + "longitude "
+ location.longitude, 5000).show();
}
});