Android开发之定位

 这里所写的定位都是原生的,也就是系统自带的定位功能。

 首先,介绍一下能够一直获取位置信息的方法,然后在介绍单独一次位置更新。在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" />
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值