Android 获取手机经纬度

在Android开发当中,经常需要用到定位功能,尤其是依赖于地理位置功能的应用,很多人喜欢使用百度地图,高德地图提供的sdk,开放API,但是在仅仅需要经纬度,或者城市,街道地址等信息,并不需要提供预览地图,地图界面的应用中,这时,不需要使用百度地图,高德地图,这样做只会增加apk的体积。

其实LocationManager,Geocoder这些Android API给我们提供的这些类就可以满足了。下面我们就来讲讲如何利用LocationManager获取经纬度

LocationUtils类代码:

package com.kf.position.positionlibrary;

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

import java.util.List;

/**
 * Created by "FLY" on 2017/3/2.
 */
public class LocationUtils {

    String TAG = "FLY.LocationUtils";

    private volatile static LocationUtils uniqueInstance;
    private LocationManager locationManager;
    private String locationProvider;
    private Location location;
    private Context mContext;

    private LocationUtils(Context context) {
        mContext = context;
        getLocation();
    }

    //采用Double CheckLock(DCL)实现单例
    public static LocationUtils getInstance(Context context) {
        if (uniqueInstance == null) {
            synchronized (LocationUtils.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new LocationUtils( context );
                }
            }
        }
        return uniqueInstance;
    }


    private void getLocation(){
        //1.获取位置管理器
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //2.获取位置提供器,GPS或是NetWork
        List providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.NETWORK_PROVIDER)){
            //如果是网络定位
            Log.d(TAG, "如果是网络定位");
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }else if (providers.contains(LocationManager.GPS_PROVIDER)){
            //如果是GPS定位
            Log.d(TAG, "如果是GPS定位");
            locationProvider = LocationManager.GPS_PROVIDER;
        }else {
            Log.d(TAG, "没有可用的位置提供器");
            return;
        }
        // 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。
        if ( Build.VERSION.SDK_INT >= 23 &&
                ActivityCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //3.获取上次的位置,一般第一次运行,此值为null
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location!=null){
            setLocation(location);
        }
        // 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
        locationManager.requestLocationUpdates(locationProvider, 5000, 3,locationListener);
    }

    private void setLocation(Location location){
        this.location =location;
        String address = "纬度:"+location.getLatitude()+"经度:"+location.getLongitude();
        Log.d(TAG,address);
    }

    //获取经纬度
    public Location showLocation(){
        return location;
    }

    // 移除定位监听
    public void removeLocationUpdatesListener() {
        // 需要检查权限,否则编译不过
        if ( Build.VERSION.SDK_INT >= 23 &&
                ActivityCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }
        if (locationManager != null) {
            uniqueInstance=null;
            locationManager.removeUpdates(locationListener);
        }
    }

    /**
     * LocationListern监听器
     * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */

    LocationListener locationListener = new LocationListener() {

        /**
         * 当某个位置提供者的状态发生改变时
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }
        /**
         * 某个设备打开时
         */
        @Override
        public void onProviderEnabled(String provider) {

        }
        /**
         * 某个设备关闭时
         */
        @Override
        public void onProviderDisabled(String provider) {

        }

        /**
         * 手机位置发生变动
         */
        @Override
        public void onLocationChanged(Location location) {
            location.getAccuracy();//精确度
            setLocation(location);
        }
    };
}


MainActivity测试代码:

package com.kf.position.positionlongitudelatitude;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.kf.position.positionlibrary.LocationUtils;

public class MainActivity extends Activity {

    private TextView textView;
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.text);
        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Location location = LocationUtils.getInstance(MainActivity.this).showLocation();
                if (location!=null){
                    String address = "纬度:"+location.getLatitude()+"经度:"+location.getLongitude();
                    Log.d("FLY.onCreate",address);
                    textView.setText(address);
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationUtils.getInstance(MainActivity.this).removeLocationUpdatesListener();
    }
}

希望对你们有帮助!!!!!

项目地址:https://github.com/MapleSunFLY/PositionLongitudeLatitude.git

你可能感兴趣的:(Android 获取手机经纬度)