Android : GPS定位 获取当前位置—简单应用

示例图:

MainActivity.java

java 复制代码
package com.example.mygpsapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Button button, btnGetData;

    //系统位置管理对象
    private LocationManager locationManager;

    private TextView textView;
    private EditText editText;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.btn_get_provider);
        textView = findViewById(R.id.tv_see);
        listView = findViewById(R.id.list_view);
        btnGetData = findViewById(R.id.btn_get_data);
        editText = findViewById(R.id.et_content);

        //1.获取系统 位置管理对象  LocationManager
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        // 2. 获取所有设备名字
        List<String> providerName = locationManager.getAllProviders();
        //2.1获取指定设备 gps
//        LocationProvider gpsProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER);

        //3 把数据放到listView 中显示
        /**3个
         * passive: 代码表示:LocationManager.PASSIVE_PROVIDER
         * gps:  代码表示:LocationManager.GPS_PROVIDER
         * network: 网络获取定位信息  LocationManager.NETWORK_PROVIDER
         * */
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, R.layout.list_layout, providerName);
        listView.setAdapter(arrayAdapter);


        //从6.0系统开始,需要动态获取权限
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Criteria 过滤 找到 定位设备
                //1.获取位置管理对象  LocationManager
                LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                //2. 创建 Criteria 过滤条件
                Criteria criteria = new Criteria();

                //要求设备是免费的
                criteria.setCostAllowed(false);
                // 要求能提供高精度信息
                criteria.setAltitudeRequired(true);
                // 要求能提供反方向信息
                criteria.setBearingRequired(true);
                //   设置精度               标准不限
//                criteria.setAccuracy(Criteria.NO_REQUIREMENT);

                // 设置功率要求  电量               标准不限
//                criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);

                //获取最佳提供商
                List<String> datas = locationManager.getAllProviders();

                textView.setText(datas.toString());
            }

        });

        //获取定位信息事件
        btnGetData.setOnClickListener(new View.OnClickListener() {
           @SuppressWarnings("all") //警告过滤
            @Override
            public void onClick(View v) {
                try {
                    //1.获取系统 位置管理对象  LocationManager
                    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                    //2.从GPS 获取最近定位信息
                    //获取到位置相关信息

                    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                    //把信息设置到文本框中
                    updatView(location);

                    //设置每3秒 获取一次Gps 定位信息
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() {
                        @Override
                        public void onLocationChanged(@NonNull Location location) {
                            //当GPS 位置发生改变时 执行方法
                            updatView(location);
                        }

                        @Override
                        public void onProviderDisabled(@NonNull String provider) {
                            //禁用时 执行方法
                            updatView(null);
                        }

                        @Override
                        public void onProviderEnabled(@NonNull String provider) {
                            // 可以用时 执行方法

                            updatView(locationManager.getLastKnownLocation(provider));
                        }


                    });


                } catch (Throwable e) {
                    e.printStackTrace();
                }


            }

        });


    }
    //把信息设置到文本框中
    public void updatView(Location location) {
        if(location != null){
            StringBuilder cont = new StringBuilder();
            cont.append("实时定位信息:\n");
            cont.append("经度:");
            cont.append(location.getLongitude());
            cont.append("\n纬度:");
            cont.append(location.getLatitude());
            cont.append("\n高度:");
            cont.append(location.getAltitude());
            cont.append("\n速度:");
            cont.append(location.getSpeed());
            cont.append("\n方向:");
            cont.append(location.getBearing());
            editText.setText(cont.toString());

        }else {
            editText.setText("没有开启定位信息!");
        }
    }
    //请求权限结果
//    ACCESS_FINE_LOCATION  访问精细定位
//    ACCESS_COARSE_LOCATION 访问粗略定位
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "访问精细定位权限授权成功", Toast.LENGTH_SHORT).show();

                    //从6.0系统开始,需要动态获取权限
                    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
                    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                    }
                }
                break;
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "访问粗略定位权限授权成功", Toast.LENGTH_SHORT).show();
                }
                break;
            default:

                break;
        }

    }
}

布局文件 activity_main.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GPS简单应用:"
        android:textSize="24sp"
        />


    <Button
        android:id="@+id/btn_get_provider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="Criteria过滤获取定位设备"
        />
    <TextView
        android:id="@+id/tv_see"
        android:textSize="24sp"
        android:textColor="#FF00ff00"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

    <TextView
       android:text="定位设备:"
        android:textSize="24sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="150dp"/>

    <Button
        android:id="@+id/btn_get_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="点击获取位置信息"
        />

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        />
</LinearLayout>

listView 布局文件 list_layout.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:textSize="20sp"
    android:textColor="#ff0f"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</TextView>

权限配置 AndroidManifest.xml

XML 复制代码
    <!-- 配置 读取位置权限
    ACCESS_FINE_LOCATION location 访问精细定位
    ACCESS_COARSE_LOCATION 访问粗略定位
     GPS-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
相关推荐
fatiaozhang95271 小时前
中兴云电脑W102D_晶晨S905X2_2+16G_mt7661无线_安卓9.0_线刷固件包
android·adb·电视盒子·魔百盒刷机·魔百盒固件
foo1st2 小时前
JDK(Ubuntu 18.04.6 LTS)安装笔记
java·笔记·ubuntu
DKPT2 小时前
常见正则表达式整理与Java使用正则表达式的例子
java·笔记·学习·面试·正则表达式
下雨的Jim2 小时前
前端速成之——Script
前端·笔记
CYRUS_STUDIO2 小时前
Android APP 热修复原理
android·app·hotfix
爱码小白2 小时前
wordpress学习笔记
笔记·学习
鸿蒙布道师3 小时前
鸿蒙NEXT开发通知工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
鸿蒙布道师3 小时前
鸿蒙NEXT开发网络相关工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
大耳猫3 小时前
【解决】Android Gradle Sync 报错 Could not read workspace metadata
android·gradle·android studio
我的golang之路果然有问题3 小时前
快速上手GO的net/http包,个人学习笔记
笔记·后端·学习·http·golang·go·net