Android GPS 动态获取地理位置

动态获取位置信息只要调用 requestLocationUpdates() 方法设置一个 LocationListener 定时检测位置即可

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
参数 说明
provider GPS 信息提供者,一般都是固定值 LocationManager.GPS_PROVIDER
minTime 当时间超过多少毫秒时更新 GPS 信息
minDistance 当位置移动多少米时更新 GPS 信息
listener 更新 GPS 时的监听器

当时间超过 minTime (单位:毫秒) 或者位置移动超过 minDistance ( 单位:米),就会调用 listener 中的方法更新 GPS 信息

建议这个 minTime 不小于 60000,即 1 分钟,这样会更加高效而且省电,如果需要尽可能实时地更新 GPS,可以将 minTimeminDistance 设置为 0

范例


  1. 创建一个 空的 Android 项目 cn.twle.android.GPSUpdate

  2. 修改 activity_location.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/ms_msg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="5dp"
            android:textSize="20sp"
            android:textStyle="bold" />
    </LinearLayout>
    
  3. 添加权限地理定位权限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  4. 修改 MainActivity.java

    package cn.twle.android.gpsupdate;
    
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.provider.Settings;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.os.Message;
    import android.os.Handler;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import static android.Manifest.permission.ACCESS_FINE_LOCATION;
    
    public class MainActivity extends AppCompatActivity {
    
        private LocationManager lm;
        private TextView ms_msg;
        private String loc_msg;
    
        private Handler handler = new Handler(new Handler.Callback(){
    
            @Override
            public boolean handleMessage(Message msg) {
                if ( msg.what == 0x001 ) {
                    ms_msg.setText(loc_msg);
                }
    
                return false;
            }
        });
    
        private LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // GPS定位信息发生改变时,更新定位
                updateShow(location);
            }
    
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
    
            }
    
            @Override
            public void onProviderEnabled(String provider) {
    
                // 如果没权限,打开设置页面让用户自己设置
                if ( checkCallingOrSelfPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
                    Toast.makeText(MainActivity.this, "请打开GPS~", Toast.LENGTH_SHORT).show();
    
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 0);
                    return;
                }
    
                // GPS LocationProvider可用时,更新定位
                updateShow(lm.getLastKnownLocation(provider));
            }
    
            @Override
            public void onProviderDisabled(String provider) {
                updateShow(null);
            }
        };
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ms_msg = (TextView) findViewById(R.id.ms_msg);
    
            lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
            locationUpdate();
        }
    
        public void onResume() {
            super.onResume();
            locationUpdate();
        }
    
        public void onPause() {
            super.onPause();
            lm.removeUpdates(mLocationListener);
        }
    
        //定义一个更新显示的方法
        private void updateShow(Location location) {
            if (location != null) {
                StringBuilder sb = new StringBuilder();
                sb.append("当前的位置信息:\n");
                sb.append("精度:" + location.getLongitude() + "\n");
                sb.append("纬度:" + location.getLatitude() + "\n");
                sb.append("高度:" + location.getAltitude() + "\n");
                sb.append("速度:" + location.getSpeed() + "\n");
                sb.append("方向:" + location.getBearing() + "\n");
                sb.append("定位精度:" + location.getAccuracy() + "\n");
    
                loc_msg = sb.toString();
            } else loc_msg = "";
    
            handler.sendEmptyMessage(0x001);
        }
    
        public void locationUpdate() {
    
            // 如果没权限,打开设置页面让用户自己设置
            if ( checkCallingOrSelfPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
                Toast.makeText(MainActivity.this, "请打开GPS~", Toast.LENGTH_SHORT).show();
    
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0);
                return;
            }
    
                Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    
                updateShow(location);
    
            // 设置间隔两秒获得一次 GPS 定位信息
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8,mLocationListener);
        }
    
    }
    

因为 GPS 不是实时更新的,一般情况下使用 LocationManager.NETWORK_PROVIDER 做一次基于网络的定位

对了,如果你发现没有调用 onLocationChanged() 不是因为代码的问题,而是,你在室内,去室外走走

别问我为什么知道,这个 bug 我修了一个下午,直到去拿快递的时候才发现更新了

参考文档

  1. 官方 API 文档:LocationManager

  2. 官方 API 文档:LocationProvider

  3. 官方 API 文档: Location

  4. 官方 API 文档: Criteria

Android 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.