1.基本使用
a.基本方法
LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);//获得LocationManager引用
locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//提供设备最后已知位置,这里有3种,GPS_PROVIDER GPS获得,NETWORK_PROVIDER网络获得,PASSIVE_PROVIDER被动提供其他应用程序提供
locMgr.getAllProviders();//返回所有能用或不能用的提供程序
locMgr.getProvider(Provider name);//返回指定提供程序
locMgr.isProviderEnabled(provider);//判断指定提供程序是否能用
locMgr.getProviders(true);//返回立即可以使用的提供程序
locMgr.getProviders(criteria, true)//返回可以使用的提供程序,并且用criteria对象指定条件
locMgr.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, // 间隔多少毫秒通知 0, // 最小间隔距离变化通知 locListener);//在onResume()中注册接收位置跟新事件的接收器
locMgr.removeUpdates(locListener);//在onPause()中删除注册
LocationListener locListener = new LocationListener(){//位置监听器//位置信息更新时调用
public void onLocationChanged(Location location)
{
if (location != null)
{
Toast.makeText(getBaseContext(),
"New location latitude [" +
location.getLatitude() +
"] longitude [" +
location.getLongitude()+"]",
Toast.LENGTH_SHORT).show();
}
}
//当禁用的提供程序被调用时会立即调用
public void onProviderDisabled(String provider)
{
}
//用户启用提供程序时被调用
public void onProviderEnabled(String provider)
{
}
//状态变化时被调用
public void onStatusChanged(String provider,
int status, Bundle extras)
{
}
};
}
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCALE_SETTINGS), 0);//请求用户打开GPS
/**LocationManager 接近提醒
*/
//geo模式:用uri的前缀来过滤数据类型
String PROX_ALERT = "com.androidbook.intent.action.PROXIMITY_ALERT";
IntentFilter iFilter = new IntentFilter(PROX_ALERT);//设置了过滤器所接受的行为 iFilter.addDataScheme("geo");//设置了过滤器说接受的uri前缀
String geo = "geo:"+lat+","+lon;
Intent intent = new Intent(PROX_ALERT, Uri.parse(geo));//在intent中添加uri匹配intentFilter
pIntent1 = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);//创建PendingIntent
locMgr.addProximityAlert(lat, lon, radius, 6000L, pIntent1);//纬度,经度,半径,超时,触发后的行为
b.所需权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />//GPS和被动提供程序所需要,也可以用于网络 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />//网络提供程序需要