Android获取当前位置的经纬度数据
现在有这么一个需求:开启一个Service服务,获取当前位置的经纬度数据,将获取的数据以广播的方式发送出去,注册广播的Activity接收广播信息,并将接收到的数据在当前Activity显示,如果当前位置发生变化,经纬度数据改变,获取改变后的经纬度数据,通过Handler发送消息,更新UI界面,显示更新后的内容,请问这样子的Demo该如何实现?
LocationTool获取当前位置信息
Android手机获取当前位置的方式:GPS定位,WIFI定位,基站定位,当前Demo使用GPS卫星定位,在LocationTool中返回Location、LocationManager两者对象,通过Location提供的getLatitude()、getLongitude()读取经纬度数据,同时添加位置改变监听器MyLocationListener,具体代码如下:
package cn.teachcourse.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.widget.Toast; /* @author postmaster@teachcourse.cn @date 创建于:2016-1-22 */ public class LocationTool { public Location getLocation() { return mLocation; } public void setLocation(Location location) { this.mLocation = location; } private Context context; private Location mLocation; private LocationManager mLocationManager; public LocationTool(Context context) { super(); mLocationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); mLocation = mLocationManager.getLastKnownLocation(getProvider()); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, new MyLocationListener(this)); } // 获取Location Provider private String getProvider() { // 构建位置查询条件 Criteria criteria = new Criteria(); // 查询精度:高 criteria.setAccuracy(Criteria.ACCURACY_FINE); // 是否查询海拨:否 criteria.setAltitudeRequired(false); // 是否查询方位角 : 否 criteria.setBearingRequired(false); // 是否允许付费:是 criteria.setCostAllowed(true); // 电量要求:低 criteria.setPowerRequirement(Criteria.POWER_LOW); // 返回最合适的符合条件的provider,第2个参数为true说明 , 如果只有一个provider是有效的,则返回当前provider return mLocationManager.getBestProvider(criteria, true); } public LocationManager getLocationManager() { return mLocationManager; } private LocationListener mLocationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { Location l = mLocationManager.getLastKnownLocation(provider); if (l != null) { mLocation = l; } } @Override public void onProviderDisabled(String provider) { mLocation = null; } @Override public void onLocationChanged(Location location) { if (location != null) { mLocation = location; } } }; public void closeLocation() { if (mLocationManager != null) { if (mLocationManager != null) { mLocationManager.removeUpdates(mLocationListener); mLocationListener = null; } mLocationManager = null; } } }
MyLocationListener位置改变监听器
LocationManager对象调用requestLocationUpdates(String provider, long minTime, float minDistance,LocationListener listener),在回调的方法中获取改变后的Location对象,其中provider表示LocationManager.GPS_PROVIDER,minTime表示最短时间间隔内更新位置信息(单位毫秒),minDistance表示最短距离内更新位置信息(单位米),MyLocationListener继承LocationListener,需要重写的方法如下:
package cn.teachcourse.utils; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; /* @author postmaster@teachcourse.cn @date 创建于:2016-1-22 */ public class MyLocationListener implements LocationListener { private LocationTool gpsTool; /**构造方法,传入LocationTool * @param gpsTool */ public MyLocationListener(LocationTool gpsTool) { super(); this.gpsTool = gpsTool; } /** * 当前位置改变后,回调onLocationChanged方法,获取改变后的Location对象 * */ @Override public void onLocationChanged(Location location) { if (location != null) { gpsTool.setLocation(location); } } /** * 当provider状态改变时回调的方法,当前的provider无法读取位置信息或者provider从无法读取位置信息变为能够读取为信息被回调的方法 * */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } /** * 当provider被用户允许开启,回调的onProviderEnabled方法,比如:开启定位功能,回调该方法 * */ @Override public void onProviderEnabled(String provider) { Location l = gpsTool.getLocationManager() .getLastKnownLocation(provider); if (l != null) { gpsTool.setLocation(l); } } /** * 当provider不被用户允许开启,回调的onProviderDisabled方法,比如:无法开启定位功能,回调该方法 * */ @Override public void onProviderDisabled(String provider) { gpsTool.setLocation(null); } }
LocationService服务读取位置信息
为什么要开启Service呢?Service和Activity、Fragment一样也有自己的生命周期,onCreate——>onStartCommand(onStart)——>onUnbind——>onRebind——>onDestroy,在LocationService执行的操作是启动一个线程获取更新后的位置信息,并以广播的方式发送出去,具体代码如下:
package cn.teachcourse.utils; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.IBinder; import android.provider.Settings; import android.widget.Toast; /* @author postmaster@teachcourse.cn @date 创建于:2016-1-22 */ public class LocationService extends Service { private LocationTool mGPSTool = null; private boolean threadDisable = false; private final static String TAG = LocationService.class.getSimpleName(); @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mGPSTool = new LocationTool(this); startThread(); } private void startThread() { new Thread(new Runnable() { @Override public void run() { while (!threadDisable) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (mGPSTool != null) { // 当结束服务时gps为空 // 获取经纬度 Location location = mGPSTool.getLocation(); // 发送广播 Intent intent = new Intent(); intent.putExtra("lat", location == null ? "" : location.getLatitude() + ""); intent.putExtra("lon", location == null ? "" : location.getLongitude() + ""); intent.setAction("cn.teachcourse.utils.GPSService"); sendBroadcast(intent); } } } }).start(); } @Override public void onDestroy() { super.onDestroy(); threadDisable = true; if (mGPSTool != null) { mGPSTool.closeLocation(); mGPSTool = null; } } @Override public IBinder onBind(Intent intent) { return null; } }
MainActivity启动服务、注册广播、显示位置信息
在MainActivity需要做的事情有:第一启动LocationService服务,调用startService()方法;第二注册广播接收器(BroadcastReceiver),创建了一个内部类MyBroadcastReceiver,继承BroadcastReceiver,重写onReceive方法;第三获取经纬度数据,更新UI界面,显示当前位置信息,具体代码如下:
//启动服务 startService(new Intent(this, LocationService.class)); //注册广播 private class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); String lon = bundle.getString("lon"); String lat = bundle.getString("lat"); if (!TextUtils.isEmpty(lon) && !TextUtils.isEmpty(lat)) { mLatitude = lat; mLongitude = lon; isObtainLoc = true; new Thread(new Runnable() { @Override public void run() { Message msg = new Message(); msg.what = REFRESH_UI;// 发送消息,通知刷新界面 mHandler.sendMessage(msg); } }).start(); } } } //更新UI界面 private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case REFRESH_UI: reFreshUI(); break; default: break; } } }; private void reFreshUI() { if (isObtainLoc) { mTextView.setText("目前经纬度\n经度:" + mLongitude + "\n纬度:" + mLatitude); mDialog.dismiss(); } }
以上就是本文的全部内容,希望对大家学习Android软件编程有所帮助。