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"/>
相关推荐
用户931356002747 分钟前
文件包含漏洞
笔记
lingggggaaaa26 分钟前
小迪安全v2023学习笔记(七十九讲)—— 中间件安全&IIS&Apache&Tomcat&Nginx&CVE
笔记·学习·安全·web安全·网络安全·中间件·apache
我登哥MVP27 分钟前
Java File 类学习笔记
java·笔记·学习
咖啡の猫1 小时前
Android开发-常用布局
android·gitee
程序员老刘2 小时前
Google突然“变脸“,2026年要给全球开发者上“紧箍咒“?
android·flutter·客户端
Tans52 小时前
Androidx Lifecycle 源码阅读笔记
android·android jetpack·源码阅读
雨白2 小时前
实现双向滑动的 ScalableImageView(下)
android
峥嵘life2 小时前
Android Studio新版本编译release版本apk实现
android·ide·android studio
天天开心a4 小时前
OSPF基础部分知识点
网络·笔记·学习·智能路由器·hcip
studyForMokey5 小时前
【Android 消息机制】Handler
android