这里所写的定位都是原生的,也就是系统自带的定位功能。
首先,介绍一下能够一直获取位置信息的方法,然后在介绍单独一次位置更新。在6.0及以上系统,使用定位功能要运行时权限。
一直获取位置信息
方法一:
//创建位置监听器
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//位置更新
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//提供者硬件状态改变会被调用
}
@Override
public void onProviderEnabled(String provider) {
//提供器启用会被调用
}
@Override
public void onProviderDisabled(String provider) {
//提供器禁用会被调用
}
}
//使用
LocationManager locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//参数一:位置提供者,这里只使用gps
//参数二:定位间隔更新时间
//参数三:定位间隔距离
//当超过定位间隔更新时间或定位间隔距离,事件就会被触发。
//参数四:位置监听器 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,0,locationListener);
//取消定位服务
locationManager.removeUpdates(locationListener);
方法二:
通过pendingintent被广播,接受广播来获取位置信息。
Intent intent = new Intent(this, LocaReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 200
, intent, PendingIntent.FLAG_UPDATE_CURRENT);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, pi);
广播接收器要静态注册的那种。
public class LocaReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//获取位置信息
Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
if(location!=null){
Log.i("123123",location.toString());
}
}
}
//取消位置服务
locationManager.removeUpdates(pi);
单独一次位置更新
如果只是想定位一下,用这个再好不过了。
方法一:
//参数一:位置提供者
//参数二:位置监听器
//参数三:置NULL
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,locationListener, null);
方法二:
//广播接收器是静态的,LocaReceiver代码没变
Intent intent = new Intent(this, LocaReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, pendingIntent);
别忘了权限。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />