LocationManager locationManager;
/**
* 初始化GPS
*/
private void initGps() {
logger.info("初始化GPS");
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 0, locationlisten);
} catch (Exception e) {
// TODO: handle exception
logger.error("gps初始化错误", e);
}
}
LocationListener locationlisten = new LocationListener() {
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
switch (arg1) { //GPS状态为可见时
case LocationProvider.AVAILABLE:
showToast("当前GPS状态为可见状态");
break; //GPS状态为服务区外时
case LocationProvider.OUT_OF_SERVICE:
showToast("当前GPS状态为服务区外状态");
break; //GPS状态为暂停服务时
case LocationProvider.TEMPORARILY_UNAVAILABLE:
showToast("当前GPS状态为暂停服务状态");
break;
}
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
// Provider被enable时触发此函数,比如GPS被打开
Location location=locationManager.getLastKnownLocation(arg0);
adn_gps.setText(Double.toString(location.getLatitude())+"/"+Double.toString(location.getLatitude()));
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
// Provider被disable时触发此函数,比如GPS被关闭
showToast("gps被关闭");
}
// 当坐标改变时触发此函数;如果Provider传进相同的坐标,它就不会被触发
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
if (arg0 != null) {
// adn_gps.setText(Double.toString(arg0.getLatitude())+"/"+Double.toString(arg0.getLongitude()));
Intent intent = new Intent("gps");
intent.putExtra("y",
Double.toString(arg0.getLatitude()));
intent.putExtra("x",
Double.toString(arg0.getLongitude()));
logger.info("X:"+Double.toString(arg0.getLongitude()));
logger.info("Y:"+Double.toString(arg0.getLatitude()));
String x = Double.toString(arg0.getLongitude());
X = x.substring(0, x.indexOf(".") + 6);// 去小数点后五位
String y = Double.toString(arg0.getLatitude());
Y = y.substring(0, y.indexOf(".") + 6);// 去小数点后五位
sendBroadcast(intent);
}
}
};
private void openGPSSettings() {
LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER))
{
showToast("GPS正常");
return;
}
Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent,0); //此为设置完成后返回到获取界面 }
}