当前位置: 首页 > news >正文

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;@Overrideprotected 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.获取系统 位置管理对象  LocationManagerlocationManager = (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() {@Overridepublic void onClick(View v) {// Criteria 过滤 找到 定位设备//1.获取位置管理对象  LocationManagerLocationManager 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") //警告过滤@Overridepublic void onClick(View v) {try {//1.获取系统 位置管理对象  LocationManagerlocationManager = (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() {@Overridepublic void onLocationChanged(@NonNull Location location) {//当GPS 位置发生改变时 执行方法updatView(location);}@Overridepublic void onProviderDisabled(@NonNull String provider) {//禁用时 执行方法updatView(null);}@Overridepublic 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 访问粗略定位@Overridepublic 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"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="GPS简单应用:"android:textSize="24sp"/><Buttonandroid:id="@+id/btn_get_provider"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="18sp"android:text="Criteria过滤获取定位设备"/><TextViewandroid:id="@+id/tv_see"android:textSize="24sp"android:textColor="#FF00ff00"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:text="定位设备:"android:textSize="24sp"android:layout_width="match_parent"android:layout_height="wrap_content"/><ListViewandroid:id="@+id/list_view"android:layout_width="match_parent"android:layout_height="150dp"/><Buttonandroid:id="@+id/btn_get_data"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="24sp"android:text="点击获取位置信息"/><EditTextandroid: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.lryc.cn/news/248535.html

相关文章:

  • 目标检测——R-CNN算法解读
  • 基于傅里叶变换的运动模糊图像恢复算法matlab仿真
  • 使用mock.js模拟数据
  • Android Handler同步屏障:深入解析
  • HT for Web (Hightopo) 使用心得(5)- 动画的实现
  • Leetcode(面试题 08.01.)三步问题
  • AIGC: 关于ChatGPT中输出表格/表情/图片/图表这些非文本的方式
  • 聊聊logback的addtivity属性
  • 在网络安全护网中,溯源是什么?
  • 【刷题】动态规划
  • hadoop操作
  • 角色管理--高级产品经理岗
  • nginx: [alert] could not open error log file
  • MySQL数据库:外键、唯一键、唯一索引
  • CSS核心功能手册:从熟悉到精通
  • 编程的重要性及解决技术难题的方法
  • 如何成为一名高效的前端开发者(10X开发者)
  • Docker port 命令
  • PostgreSQL-SQL联表查询LEFT JOIN 数据去重复
  • Golang与MongoDB的完美组合
  • 初识Java 18-2 泛型
  • vue分环境打包及案例代码
  • 基于springboot+vue的在线考试系统(前后端分离)
  • 重装linux后需要做的配置
  • 【华为数通HCIP | 网络工程师】821刷题日记-IS-IS(2)
  • Linux系统-----进程管理(进程的创建与控制)
  • Unity 获取物体的子物体的方法
  • RocketMQ 读写压测
  • PHP调用API接口的方法及实现(一键采集淘宝商品详情数据)
  • 得物App安卓冷启动优化-Application篇