android gps 获取方位_在Android上获取当前GPS位置

I'm trying to get the user's current location via GPS capability,

Wrote a simple class that implements LocationListener

public class LocationManagerHelper implements LocationListener {

private static double latitude;

private static double longitude;

@Override

public void onLocationChanged(Location loc) {

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) {

// TODO Auto-generated method stub

}

public static double getLatitude() {

return latitude;

}

public static double getLongitude() {

return longitude;

}

}

and from a simple Action I'm accessing these longitude and latitude values

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

/** create a TextView and write Hello World! */

TextView tv = new TextView(this);

LocationManager mlocManager =

(LocationManager) getSystemService(Context.LOCATION_SERVICE);

LocationListener mlocListener = new LocationManagerHelper();

mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,

mlocListener);

if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

tv.append("Latitude:- " + LocationManagerHelper.getLatitude()

+ '\n');

tv.append("Longitude:- " + LocationManagerHelper.getLongitude()

+ '\n');

} else {

tv.setText("GPS is not turned on...");

}

/** set the content view to the TextView */

setContentView(tv);

But it always returns 0.0 as the result.Couldn't figure out the problem.

解决方案

Your location update callbacks can't be fired until after onCreate() returns. If you initialize your lat/long variables to dummy values you will probably see you are printing those values.

Put some logging in your onLocationChanged so that you can see it's being fired, then read up a bit on how android applications work with regard to callbacks and updating the UI.

Also make sure your application has appropriate permissions in its manifest.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值