您的位置:首页 > 移动开发 > Android开发

Android范例编程一:获取地理位置

2016-03-20 16:15 447 查看
这一系列文章的目的是以单个需求为向导,十分钟左右能完成的Android范例编程。

前言:现在商业化的APP中不去获取用户位置信息的基本上没有,有的根据没有位置需求的也要请求下获取位置,可见是个标配需求了。从网上搜索到的相关信息没有关于请求更新后通过Looper和Handler来移除监听。

流程:

启动时获取系统位置服务

获得主线程Looper,在请求位置更新时传入Looper和位置更新监听器

创建一个Handler,提交消息,在指定时间移除监听

顺便实现了一下持续获取地理位置

Activity转入后台时移动监听器

编写:

启动Android Studio,创建一个新工程,命名为AndroidGPS.

在MANIFAST中添加访问GPS的权限

在默认生成的布局文件中将TextView居中,命名,并添加一个Button

转到Activity中,添加成员变量

private TextView textView;
private Location location;
private LocationManager locationManager;
private LocationListener listener;
private Runnable runnable;
private Handler handler;


在onCreate方法中,添加下列代码
textView = (TextView) findViewById(R.id.tv_info);
textView.setText("正在获取经纬度信息……");
listener = new MyListener();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
runnable = new MyRunnable();
Looper looper = Looper.myLooper();
handler = new Handler(looper);
handler.postDelayed(runnable,60000);
locationManager.requestSingleUpdate(GPS_PROVIDER, listener, looper);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.removeUpdates(listener);
handler.removeCallbacks(runnable);
locationManager.requestLocationUpdates(GPS_PROVIDER,1000,0,listener);
}
});


添加一个内部类,实现LocationListener接口,并实现onLocationChanged方法

class MyListener implements LocationListener{
@Override
public void onLocationChanged(Location location) {
GPSActivity.this.location = location;
textView.setText("经度:" + location.getLongitude()
+ "\n纬度:" + location.getLatitude());
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}

@Override
public void onProviderEnabled(String provider) {}

@Override
public void onProviderDisabled(String provider) {}
}


再添加一个内部类,实现Runnable接口
class MyRunnable implements Runnable{
@Override
public void run() {
locationManager.removeUpdates(listener);
if (location == null){
textView.setText("获取位置失败");
}else{
textView.setText("经度:" + location.getLongitude()
+ "\n纬度:" + location.getLatitude());
}
}
}


重写Activity中的onStop方法移除监听器
@Override
protected void onStop() {
locationManager.removeUpdates(listener);
handler.removeCallbacks(runnable);
super.onStop();
}


连带系统引用的包和自动生成的方法签名不到九十行。一个完整可用的位置获取程序就出来了。

延伸:一句话知识点

Android:

Activity-Android四大组件之一,做过web开发的,可以理解为MVC中的C,控制器。后续会专门写一篇文章讲讲我的理解。

Handler与Looper:Android中的消息处理框架,常用于UI更新,线程间通讯。

JAVA:

内部类的使用

Runnable JAVA中多线程的经常要使用的接口

声明父类,实例化子类,这是实现多态

所有代码已传上Github,点击原文链接可以看到,懒得写的可以直接clone下载

或者

git clone https://github.com/songgois/AndroidGPS.git
我的个人微信公众号:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: