思路原理:
(1)获取LocationManager实例,通过getSystemService方法,传入Context.LOCATION_SERVICE参数。
(2)获取可用的位置提供器,有GPS_PROVIDER、NETWORK_PROVIDER、PASSIVE_PROVIDER三种,前两种比较常用。
(3)将(2)获取到的位置提供器传入LocationManager的方法getLastKnownLocation,即可获取Location信息。
如果移动设备地理位置不断发生变化,则实时更新需要进行如下步骤:
(4)调用LocationManager的requestLocationUpdates方法,第一个参数是位置提供器,第二个参数是监听位置变化的时间间隔(毫秒),第三个参数是监听位置变化的距离间隔(米),第四个参数是LocationListener监听器
(5)当位置发生变化后,就会调用监听器的onLocationChanged方法。
(6)为了省电,节约资源,当程序关闭后,调用LocationManager的removeUpdates方法移除监听器。
获取权限
修改AndroidManifest.xml,添加如下代码:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
代码片段
package com.example.locationtest;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
LocationManager locationManager;
TextView textView;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// 获取location对象
location = getBestLocation(locationManager);
updateView(location);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 8, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
updateView(locationManager
.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
updateView(null);
}
@Override
public void onLocationChanged(Location location) {
location = getBestLocation(locationManager);// 每次都去获取GPS_PROVIDER优先的location对象
updateView(location);
}
});
}
private void updateView(Location location) {
if (location != null) {
StringBuffer sb = new StringBuffer();
sb.append("位置信息:\n");
sb.append("经度:" + location.getLongitude() + ", 纬度:"
+ location.getLatitude());
textView.setText(sb.toString());
} else {
textView.setText("");
}
}
/**
* 获取location对象,优先以GPS_PROVIDER获取location对象,当以GPS_PROVIDER获取到的locaiton为null时
* ,则以NETWORK_PROVIDER获取location对象,这样可保证在室内开启网络连接的状态下获取到的location对象不为空
*
* @param locationManager
* @return
*/
private Location getBestLocation(LocationManager locationManager) {
Location result = null;
if (locationManager != null) {
result = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (result != null) {
return result;
} else {
result = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return result;
}
}
return result;
}
}