关闭

使用Andorid原生工具类获取手机经纬度

标签: androidgps地图
2199人阅读 评论(0) 收藏 举报

对于不使用任何第三方地图sdk的设备,可以直接获取gps传感器,基站传感器,wifi传感器所获取的经纬度,一般写一个service放在后台,代码如下


import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class LocationUpdateService extends IntentService {
    private final int MAX_DIVIDER = 600000;
    private final int MIN_DIVIDER = 15000;
    private final int PROVIDER_DISABLED = 3000;
    private ArrayList<String> PROVIDER_ARRAY;

    public static double latitude = 0d;//用于记录当前的纬度
    public static double longitude = 0d;//用于记录当前的经度

    private boolean isDestory;
    private String locationProvider;
    private LocationManager locationManager;
    private LocationListener gpsLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
        }

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

        @Override
        public void onProviderEnabled(String provider) {
            getBestLocationProvider();
        }

        @Override
        public void onProviderDisabled(String provider) {
            getBestLocationProvider();
        }
    };
    private LocationListener networkLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
        }

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

        @Override
        public void onProviderEnabled(String provider) {
            getBestLocationProvider();
        }

        @Override
        public void onProviderDisabled(String provider) {
            getBestLocationProvider();
        }
    };
    private LocationListener passiveLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {//这个方法不用写,写了也没用
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {//这个方法不用写,写了也没用
        }

        @Override
        public void onProviderEnabled(String provider) {
            getBestLocationProvider();
        }

        @Override
        public void onProviderDisabled(String provider) {
            getBestLocationProvider();
        }
    };

    public LocationUpdateService() {
        super("haha");
        PROVIDER_ARRAY = new ArrayList<>();
        PROVIDER_ARRAY.add(LocationManager.GPS_PROVIDER);
        PROVIDER_ARRAY.add(LocationManager.NETWORK_PROVIDER);
        PROVIDER_ARRAY.add(LocationManager.PASSIVE_PROVIDER);
        isDestory = false;
    }

    /**
     * 获取目前最精准的地理位置传感器
     */
    private synchronized void getBestLocationProvider() {//synchronized 是Java语言的关键字,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。
        if (locationManager == null) {//如果android不支持locationManager,就算了
            locationProvider = null;
            return;
        }

        List<String> providers = locationManager.getAllProviders();
        //遍历所有的传感器
        for (String provider:providers) {
            JLogUtils.i("Alex","发现位置传感器"+provider);
        }
        if (providers == null || providers.size() <= 0) {
            locationProvider = null;
            return;
        }

        String bestProvider = null;
        Location bestLocation = null;//android原生location对象
        for (String provider : providers) {
            if ((provider != null) && (PROVIDER_ARRAY.contains(provider))) {
                Location location = locationManager.getLastKnownLocation(provider);
                if (location == null) {
                    continue;
                }

                //筛选出最精准的传感器
                if (bestLocation == null) {
                    bestLocation = location;
                    bestProvider = provider;
                    continue;
                }

                if (Float.valueOf(location.getAccuracy()).compareTo(bestLocation.getAccuracy()) >= 0) {
                    bestLocation = location;
                    bestProvider = provider;
                }
            }
        }

        locationProvider = bestProvider;
    }

    /**
     * 给locationManager实例化
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        locationProvider = null;
        locationManager = null;

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return;
        }

        List<String> allProviders = locationManager.getAllProviders();
        if (allProviders != null) {
            for (String provider : allProviders) {
                Log.i("Alex","全部传感器列表:"+provider);
                if ((provider != null) && (PROVIDER_ARRAY.contains(provider))) {
                    if (LocationManager.GPS_PROVIDER.equals(provider)) {
                        Log.i("gps","正在使用gps传感器");
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, gpsLocationListener);
                    } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
                        Log.i("gps","正在使用流基站感器");
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, networkLocationListener);
                    } else if (LocationManager.PASSIVE_PROVIDER.equals(provider)) {
                        Log.i("gps","正在使用被动传感器");
                        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 10000, 0, passiveLocationListener);
                    }
                }
            }
        }

        while (!isDestory) {
            getBestLocationProvider();

            updateLocation();

            if ((locationProvider != null) && (PROVIDER_ARRAY.contains(locationProvider))) {
                try {
                    if ((compare(latitude, 0.0) == 0)//看看现在有没有具体的定位,并让传感器休息一段时间
                            && (compare(longitude(), 0.0) == 0)) {
                        Thread.sleep(MIN_DIVIDER);
                    } else {
                        Thread.sleep(MAX_DIVIDER);
                    }
                } catch (InterruptedException ex) {
                }
            } else {
                try {
                    Thread.sleep(PROVIDER_DISABLED);
                } catch (Exception ex) {
                }
            }
        }
    }

    private void updateLocation() {
        if ((locationProvider != null) && (!locationProvider.equals("")) && (PROVIDER_ARRAY.contains(locationProvider))) {
            try {
                Location currentLocation = locationManager.getLastKnownLocation(locationProvider);//获取最新位置
                if (currentLocation != null) {
                    //获取经纬度
                    final double newLatitude = currentLocation.getLatitude();
                    final double newLongitude = currentLocation.getLongitude();
                    latitude = newLatitude;
                    longitude = newLongitude;
                    Log.i("gps","当前纬度是:"+newLatitude+"当前经度是:"+newLongitude);


                }
            } catch (Exception ex) {
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestory = true;

        if ((locationManager != null) && (gpsLocationListener != null)) {
            locationManager.removeUpdates(gpsLocationListener);
        }

        if ((locationManager != null) && (networkLocationListener != null)) {
            locationManager.removeUpdates(networkLocationListener);
        }

        if ((locationManager != null) && (passiveLocationListener != null)) {
            locationManager.removeUpdates(passiveLocationListener);
        }
    }

    /**
     * 用于对传入的数据进行限幅操作
     * @param left
     * @param right
     * @return
     */
    public static int compare(double left, double right) {
        if (Double.isInfinite(left) && Double.isInfinite(right)) {
            return 0;
        }
        if (Double.isInfinite(left)) {
            return 1;
        }
        if (Double.isInfinite(right)) {
            return -1;
        }

        if (Double.isNaN(left) && Double.isNaN(right)) {
            return 0;
        }
        if (Double.isNaN(left)) {
            return -1;
        }
        if (Double.isNaN(right)) {
            return 1;
        }

        BigDecimal val1 = new BigDecimal(left);
        BigDecimal val2 = new BigDecimal(right);
        int result = -2;
        if (val1.compareTo(val2) < 0) {
            result = -1;
        } else if (val1.compareTo(val2) == 0) {
            result = 0;
        } else if (val1.compareTo(val2) > 0) {
            result = 1;
        }
        return result;
    }
}

调用方法:

public class HahaActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_haha);
        startService(new Intent(this, IMGLocationUpdateService.class));//启动位置定位服务

        new Thread(){
            @Override
            public void run() {
                try {
                    sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.i("gps", "当前经纬度"+ LocationUpdateService.latitude+":"+LocationUpdateService.longitude);
            }
        }.start();
    }

}


4
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

Android获取手机经纬度(GPS、NetWork)封装工具类

简单封装了一下,获取简单,看代码: import android.content.Context; import android.location.Location; import androi...
  • yy1300326388
  • yy1300326388
  • 2015-08-06 11:33
  • 6286

Android 如何获取手机经纬度和地理位置信息

最近做项目需要用到获取手机地理位置信息用Android自带的LocationManager和Location获取位置的时候,经常会有获取的location为null的情况(在室外能获取到位置信息,但在...
  • gaolei1201
  • gaolei1201
  • 2014-11-14 10:42
  • 3750

Android获取手机经纬度(GPS、NetWork)封装工具类

(1)获取LocationManager实例,通过getSystemService方法,传入Context.LOCATION_SERVICE参数。 (2)获取可用的位置提供器,有GPS_PROVID...
  • qq_29443203
  • qq_29443203
  • 2017-12-16 15:55
  • 65

java工具类(一)之服务端java实现根据地址从百度API获取经纬度

服务端java实现根据地址从百度API获取经纬度 代码:  package com.pb.baiduapi; import java.io.BufferedReader; import java....
  • sunhuaqiang1
  • sunhuaqiang1
  • 2015-07-31 08:08
  • 51124

Android 高德获取经纬度工具类

以上就能获取定位并且能够计算两地的距离了。
  • qq939782569
  • qq939782569
  • 2017-01-03 15:29
  • 768

获取当前经纬度、当前位置省市区(工具类)

// // YALocationInfo.h // YATestFramework // // Created by MacDev1 on 15/6/25. // Copyright (c) ...
  • gaojq_ios
  • gaojq_ios
  • 2016-03-30 18:03
  • 2439

自己封装的工具类,使用原生SwipeRefreshLayout+RecycleView实现下拉刷新和加载更多

实现SwipeRefreshLayout+RecycleView实现刷新在你的xml文件里写上如下代码: <android.support.v4.widget.SwipeRefreshL...
  • DyncKathline
  • DyncKathline
  • 2016-09-18 11:45
  • 539

使用Java原生API编写发送HTTP_POST请求的工具类

完整版见https://jadyer.github.io/
  • jadyer
  • jadyer
  • 2013-03-05 11:43
  • 3467

Andorid开发工具类之——BitmapUtils(压缩图片利器,告别oom,程序更快)

最近开发的一个项目使用到了图片加载上传和保存,由于是接受别人的做,也基本上做完了。但是程序已启动到需要加载图片上传到服务器的界面的时候内存就暴涨,虽然也没有oom,估计旧点的手机肯定会爆,只要不启动到...
  • zy517863543
  • zy517863543
  • 2016-12-21 14:32
  • 1565

Andorid开发工具类之——SPUtils

SharedPreferences 是开发中经常用到的保存数据的一种方式,之前在网上看到一些类似的工具类,但是都没有达到理想的要求,搜集了网上的资料后自己又改造了代码,现在达到了理想的要求,上代码: ...
  • zy517863543
  • zy517863543
  • 2016-12-21 13:58
  • 2099
    个人资料
    • 访问:519446次
    • 积分:5761
    • 等级:
    • 排名:第5244名
    • 原创:149篇
    • 转载:0篇
    • 译文:1篇
    • 评论:214条
    最新评论