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"/>
相关推荐
疯狂打码的少年1 小时前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
马上去吃汉堡王1 小时前
Windows11安装Geant4
笔记
一笑的小酒馆1 小时前
Android视频直播播放器简单封装
android
气泡水。1 小时前
RHCSA笔记实记
linux·笔记
祈禾2 小时前
Redis三大特殊数据类型
运维·服务器·数据库·redis·笔记·缓存
祈禾2 小时前
计算机组成原理之编译、汇编、链接、解释
开发语言·汇编·笔记·学习
工会代表3 小时前
安卓手机搭建SOCKS5代理教程
android
雨白3 小时前
Android AOP 切面编程实战:优雅地处理全局断网拦截
android·架构
s1ckrain4 小时前
XR笔记-Extended Reality核心概念总结
笔记·xr·具身智能
huluang5 小时前
专业级安卓现场取证利器:拍照取证(PaiZaoXue),补齐行业取证工具核心短板
android·数码相机