android开发怎么自动定位

       最近,我做了一个项目(新手练习),里面有段功能是要自动定位到当前位置,以下是代码:

首先需要导入jar包

android-studio导入jar包步骤请看http://jingyan.baidu.com/article/e6c8503c7190b7e54f1a1893.html

eclipse导入jar包步骤请看http://jingyan.baidu.com/article/59703552c3fc808fc1074045.html?st=2&os=0&bd_page_type=1&net_type=2

新建一个类 :

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import java.io.IOException;
import java.util.List;

/**
 * Created by dell on 2016/10/30.
 */
public class LocationUtils {
    public static String cityName;   //城市名
    private static Geocoder geocoder;  //此对象能通过经纬度来获取相应的城市等信息

    //通过地理坐标获取城市名 其中CN分别是city和name的首字母缩写
    public static void getCNBylocation(Context context) {
        geocoder = new Geocoder(context);
        //用于获取Location对象,以及其他
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        //实例化一个LocationManager对象
        locationManager = (LocationManager) context.getSystemService(serviceName);
        //provider的类型
        String provider = LocationManager.NETWORK_PROVIDER;

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);    //低精度   高精度:ACCURACY_FINE
        criteria.setAltitudeRequired(false);       //不要求海拔
        criteria.setBearingRequired(false);       //不要求方位
        criteria.setCostAllowed(false);      //不允许产生资费
        criteria.setPowerRequirement(Criteria.POWER_LOW);   //低功耗

        //通过最后一次的地理位置来获取Location对象
        Location location = locationManager.getLastKnownLocation(provider);
        if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        String queryed_name = updateWithNewLocation(location);
        if((queryed_name!=null)&&(0!=queryed_name.length())){
            cityName = queryed_name;
        }
        /*
        第二个参数表示更新的周期,单位为毫秒,
        第三个参数的含义表示最小距离间隔,单位是米,设定每30秒进行一次自动定位
        */
        locationManager.requestLocationUpdates(provider, 30000, 50, locationListener);
        //移除监听器,在只有一个widget的时候,这个还是适用的
        locationManager.removeUpdates(locationListener);
    }
    //方位改变是触发,进行调用
    private final static LocationListener locationListener = new LocationListener() {
        String tempCityName;
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
            tempCityName = updateWithNewLocation(null);
            if((tempCityName!=null)&&(tempCityName.length()!=0)){
                cityName = tempCityName;
            }
        }
        @Override
        public void onLocationChanged(Location location) {
            tempCityName = updateWithNewLocation(location);
            if((tempCityName!=null)&&(tempCityName.length()!=0)){
                cityName = tempCityName;
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }
    };
    //更新location  return cityName
    private static String updateWithNewLocation(Location location){
        String mcityName = "";
        double lat = 0;
        double lng = 0;
        List<Address> addList = null;
        if(location!=null){
            lat = location.getLatitude();
            lng = location.getLongitude();
        }else{
            cityName = "无法获取地理信息";
        }
        try {
            addList = geocoder.getFromLocation(lat, lng, 1);    //解析经纬度
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(addList!=null&&addList.size()>0){
            for(int i=0;i<addList.size();i++){
                Address add = addList.get(i);
                mcityName += add.getLocality()+add.getSubLocality()+add.getThoroughfare();
            }
        }
        Log.e("mcityName",mcityName);
        return mcityName;
    }
}
updateWithNewLocation方法中的

getCountryName()可以得到国家,如"中国"

getCountryCode 可以得到国家的代码 如 131
getLocality()可以得到市 ,如"北京市"
getSubLocality()是得到区 , "房山区"
getThoroughfare()可以得到街道
如果您还有什么问题欢迎留言,大家一起讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值