声明:需先申请百度密钥,导入百度sdk,配置百度定位环境(具体如何实现请看http://blog.csdn.net/u011176265/article/details/50427965)
public class MainActivity extends FragmentActivity implements OnClickListener {
/* 定位相关 */
/** 实现定位的API */
private LocationClient locationClient;
/** 定位监听器 */
private MyLocationListener locationListener;
/** 定位城市 */
private TextView tvLocationCity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 在使用SDK各组件之前初始化context信息,传入ApplicationContext
// 注意该方法要再setContentView方法之前实现
/**
* 在SDK各功能组件使用之前都需要调用
* SDKInitializer.initialize(getApplicationContext());
* 因此我们建议该方法放在Application的初始化方法中
*/
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
initLocation();
}
/**初始化定位*/
private void initLocation() {
locationClient = new LocationClient(getApplicationContext());
locationListener = new MyLocationListener();
locationClient.registerLocationListener(locationListener);
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy); //设置定位模式
option.setCoorType("bd09ll"); //坐标类型
option.setIsNeedAddress(true); //是否返回当前位置
option.setOpenGps(true); //是否打开GPS
option.setScanSpan(5000); //每隔5秒进行一次请求
locationClient.setLocOption(option);
}
private class MyLocationListener implements BDLocationListener{
/**定位成功后的回调*/
@Override
public void onReceiveLocation(BDLocation location) {
if(location == null){
Toast.makeText(MainActivity.this, "定位失败", Toast.LENGTH_SHORT).show();
}
tvLocationCity.setText(location.getCity());
Toast.makeText(MainActivity.this, "定位成功:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>protected void onStart() {
<span style="white-space:pre"> </span>// TODO Auto-generated method stub
<span style="white-space:pre"> </span>super.onStart();
<span style="white-space:pre"> </span>locationClient.start();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>protected void onStop() {
<span style="white-space:pre"> </span>// TODO Auto-generated method stub
<span style="white-space:pre"> </span>super.onStop();
<span style="white-space:pre"> </span>locationClient.stop();
<span style="white-space:pre"> </span>}
}