android原生定位

public class LocationUtils {
    public static int GPS_REQUEST_CODE = 999;
    private LocationManager locationManager;
    private static final int REQUEST_CONTACTS = 1;
    private static final String[] PERMISSIONS_CONTACT = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    private Location location;
    static LocationUtils locationUtils;
    private BaseActivity activity;
    private double latitude = 0, longitude = 0;
    private int count;
    private boolean isHavaLocation;

    public static LocationUtils getInstance() {
        if (locationUtils == null) locationUtils = new LocationUtils();
        return locationUtils;
    }

    public void getLocations(final BaseActivity activity) {
        this.activity = activity;
        initLocation();
    }

    private void initLocation() {
        if (!isHavaLocation) {
            try {
                locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
                List<String> providers = locationManager.getProviders(true);
                String locationProvider = null;
                if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                    locationProvider = LocationManager.NETWORK_PROVIDER;
                } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
                    locationProvider = LocationManager.GPS_PROVIDER;
                }
                if (Build.VERSION.SDK_INT >= 23) {
                    if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                            || ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        requestSetPermissions();
                    }
                }
                if(locationProvider != null){
                    while (null == location && count < 3 && !isHavaLocation) {
                        count += 1;
                        isHavaLocation = false;
                        location = locationManager.getLastKnownLocation(locationProvider);
                    }
                    if (location != null) {
                        isHavaLocation = true;
                        longitude = location.getLongitude();
                        latitude = location.getLatitude();
                    }//end of if
                    locationManager.requestLocationUpdates(locationProvider, 100l, 0f, locationListener);
                }else {
                    System.out.println("==================> locationProvider 为null");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if(!activity.isDestroyed()){
                            DubDialogUtils.showOklDialog(activity, "请打开网络或GPS", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                                        //if(!activity.isDestroyed()) activity.finish();
                                    }
                                }
                            });
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("定位异常:" + e.getMessage());
            }
        }
    }

    private void requestSetPermissions() {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_COARSE_LOCATION) ||
                ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(activity, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        }
    }

    public LocationListener locationListener = new LocationListener() {

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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            location.getAccuracy();//精确度
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    };

    public void removeLocationManager() {
        if (null != locationManager) locationManager.removeUpdates(locationListener);
        if (locationUtils != null) locationUtils = null;
        isHavaLocation = true;
    }

    public void openLocationGPS(final BaseActivity activity){
        if(null != activity){
            if(NotNetWork.isNetworkAvailable(activity)){
               //跳转GPS设置界面
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            activity.startActivityForResult(intent, GPS_REQUEST_CODE);
          }
    }

    private static String gpsInfoConvert(double gpsInfo) {
        gpsInfo = Math.abs(gpsInfo);
        String dms = Location.convert(gpsInfo, Location.FORMAT_SECONDS);
        String[] splits = dms.split(":");
        String[] secondAry = (splits[2]).split("\\.");
        String seconds;
        if (secondAry.length == 0) {
            seconds = splits[2];
        } else {
            seconds = secondAry[0];
        }
        return splits[0] + "/1," + splits[1] + "/1," + seconds + "/1";
    }

    /**
     * @param latitude  经度
     * @param longitude 纬度
     * @return 详细位置信息 GeoCoder是基于后台backend的服务,因此这个方法不是对每台设备都适用。
     */
    public String convertAddress(Context context, double latitude, double longitude) {
        Geocoder mGeocoder = new Geocoder(context, Locale.getDefault());
        StringBuilder mStringBuilder = new StringBuilder();
        try {
            List<Address> mAddresses = mGeocoder.getFromLocation(latitude, longitude, 1);
            if (!mAddresses.isEmpty()) {
                Address address = mAddresses.get(0);
                mStringBuilder.append(address.getCountryName()).append(", ").append(address.getAdminArea()).append(", ").append(address.getLocality());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mStringBuilder.toString();
    }

    public interface OnWritePictureExifInfoListener {
        void onWritePictureExifInfo(boolean isSuccess);
    }
}

清单加上权限及配置

<uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps" />

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值