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

示例图:

MainActivity.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 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 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

    <!-- 配置 读取位置权限
    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"/>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/201854.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

CentOS7安装MiniO

目录 1、简介 2、安装 2.1、Binary 2.2、RPM&#xff08;RHEL&#xff09;就是红帽&#xff0c;CentOS就用这个 2.3、DEB&#xff08;Ubuntu/Debian&#xff09; 2.4、创建指定的目录并且将下载的安装包上传上去 3、启动MiniO服务 3.1、脚本如下&#xff1a; 4、进入服务…

汽车悬架底盘部件自动化生产线3d检测蓝光三维测量自动化设备-CASAIM-IS(2ND)

随着汽车工业的不断发展&#xff0c;对于汽车零部件的制造质量和精度要求也在不断提高。汽车悬架底盘部件作为汽车的重要组成部分&#xff0c;其制造质量和精度直接影响到整车的性能和安全性。因此&#xff0c;采用CASAIM-IS&#xff08;2ND&#xff09;蓝光三维测量自动化设备…

机器学习与 S3 相集成 :释放数据的力量

文章作者&#xff1a;Libai 引言 在当今数据驱动的世界中&#xff0c;企业不断寻求如何高效利用企业自身所产生的数据的解决方案。机器学习已经成为一种提取有价值的见解和做出数据驱动决策的强大工具。然而&#xff0c;机器学习模型的成功在很大程度上依赖于高质量数据的可用…

基于Vue.js的厦门旅游电子商务预订系统的设计和实现

项目编号&#xff1a; S 030 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S030&#xff0c;文末获取源码。} 项目编号&#xff1a;S030&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 景点类型模块2.2 景点档案模块2.3 酒…

【开源视频联动物联网平台】视频AI智能分析部署方式

利用视频监控的AI智能分析技术&#xff0c;可以让视频监控发挥更大的作用&#xff0c;成为管理者的重要决策工具。近年来&#xff0c;基于视频监控的AI分析算法取得了巨大的发展&#xff0c;并在各种智慧化项目中得到了广泛应用&#xff0c;为客户提供更智能化的解决方案。 然…

【智能算法】季节优化算法Seasons optimization algorithm【2023最新智能优化算法合集】

本文介绍了一种基于成吉思汗鲨鱼(Genghis Khan shark&#xff0c;GKS)行为的自然启发的元启发式算法(MA)&#xff0c;称为成吉思汗鲨鱼优化器(Genghis Khan shark optimizer&#xff0c;GKSO)&#xff0c;用于数值优化和工程设计。GKSO的灵感来自于GKS的捕食和生存行为。该成果…

进程间通信基础知识【Linux】——上篇

目录 一&#xff0c;理解进程之间的通信 1. 进程间通信目的 2. 进程间通信的技术背景 3&#xff0c;常见的进程间通信 二&#xff0c;管道 1. 尝试建立一个管道 管道的特点&#xff1a; 管道提供的访问控制&#xff1a; 2. 扩展&#xff1a;进程池 阶段一&#xff1a…

【实验】配置用户自动获取IPv6地址的案例

热门IT课程-试听视频文章浏览阅读49次。认证课程介绍&#xff1a;华为HCIA试听课程 &#xff1a; 华为HCIA试听课程&#xff1a;华为HCIA试听课程&#xff1a;华为HCIP试听课程&#xff1a;思科CCNA试听课程&#xff1a;思科CCNA试听课程&#xff1a;思科CCNA试听课程&#xff…

回归预测 | MATLAB实现基于LightGBM算法的数据回归预测(多指标,多图)

回归预测 | MATLAB实现基于LightGBM算法的数据回归预测&#xff08;多指标&#xff0c;多图&#xff09; 目录 回归预测 | MATLAB实现基于LightGBM算法的数据回归预测&#xff08;多指标&#xff0c;多图&#xff09;效果一览基本介绍程序设计参考资料 效果一览 基本介绍 MATLA…

高效办公:如何使用视频剪辑工具批量转码,mp4视频到TS视频

在视频处理过程中&#xff0c;转码是一项常见的任务。将MP4视频转换为TS视频可以提供许多优势&#xff0c;包括更好的兼容性、更广泛的设备和平台支持以及更高的视频质量。然而&#xff0c;手动转码大量视频文件可能会非常耗时且效率低下。为了实现高效办公&#xff0c;可以使用…

内存函数​(memcpy、memmove、memset、memcmp)

目录 一、memcpy的使用和实现 使用&#xff1a; 模拟实现&#xff1a; 二、memmove 使用和模拟实现 模拟实现&#xff1a; 2.1难点&#xff1a; 覆盖拷贝所在的问题 memset的使用 memcmp的函数的使用​ 一、memcpy的使用和实现 memcpy 拷贝的就是不重叠的内存。 参数…

webpack如何处理浏览器的样式兼容问题postcss

一、准备工作 css/index.css添加样式 .word {color: red;user-select: none; } 为了兼容不同的浏览器我们需要添加前缀比如&#xff1a; -webkit-user-select: none; 这个工作可以通过postcss的插件postcss-preset-env处理 二、安装依赖 pnpm i -D postcss postcss-loader…

TCP 连接建立

1&#xff1a;TCP 三次握手过程是怎样的&#xff1f; 客户端和服务端都处于 CLOSE 状态&#xff0c;服务端主动监听某个端口&#xff0c;处于 LISTEN 状态 第一次握手&#xff1a;客户端带着序号和SYN为1&#xff0c;把第一个 SYN 报文发送给服务端&#xff0c;客户端处于 SYN-…

C库函数—sprintf

函数介绍&#xff1a; C 库函数 int sprintf(char *str, const char *format, ...) 发送格式化输出到 str 所指向的字符串。 参数&#xff1a; str -- 这是指向一个字符数组的指针&#xff0c;该数组存储了 C 字符串。format -- 这是字符串&#xff0c;包含了要被写入到字符串 …

[架构之路-254]:目标系统 - 设计方法 - 软件工程 - 软件设计 - 架构设计 - 全程概述

目录 一、软件架构概述 1.1 什么是软件架构 1.2 为什么需要软件架构设计 1.3 软件架构设计在软件设计中位置 &#xff08;1&#xff09;软件架构设计&#xff08;层次划分、模块划分、职责分工&#xff09;&#xff1a; &#xff08;2&#xff09;软件高层设计、概要设计…

JVM执行引擎以及调优

1.JVM内部的优化逻辑 1.1JVM的执行引擎 javac编译器将Person.java源码文件编译成class文件[我们把这里的编译称为前期编译]&#xff0c;交给JVM运行&#xff0c;因为JVM只能认识class字节码文件。同时在不同的操作系统上安装对应版本的JDK&#xff0c;里面包含了各自屏蔽操作…

LeetCode(36)旋转图像【矩阵】【中等】

目录 1.题目2.答案3.提交结果截图 链接&#xff1a; 48. 旋转图像 1.题目 给定一个 n n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。 你必须在** 原地** 旋转图像&#xff0c;这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。 …

【数据挖掘】国科大刘莹老师数据挖掘课程作业 —— 第二次作业

Written Part 1. 给定包含属性&#xff5b;Height, Hair, Eye&#xff5d;和两个类别&#xff5b;C1, C2&#xff5d;的数据集。构建基于信息增益&#xff08;info gain&#xff09;的决策树。 HeightHairEyeClass1TallBlondBrownC12TallDarkBlueC13TallDarkBrownC14ShortDark…

基于Qt QChart和QChartView实现正弦、余弦、正切图表

# 源码地址 https://gitcode.com/m0_45463480/QChartView/tree/main# .pro QT += charts​​HEADERS += \ chart.h \ chartview.h​​SOURCES += \ main.cpp \ chart.cpp \ chartview.cpp​​target.path = $$[QT_INSTALL_EXAMPLES]/charts/zoomlinechartINSTAL…

用customize-cra+react-app-rewired配置less+css module

1. 安装 npm i less less-loader -D npm i customize-cra-less-loader -D2.添加配置项 //config-overrides.js const { override } require(customize-cra); const addLessLoader require("customize-cra-less-loader");module.exports {webpack: override(addL…