代码依旧是kotlin编写,java类似

1、在清单文件里添加权限

<!--请求网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 这个权限用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 这个权限用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

2、新建工具类LocationUtils

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.util.Log@SuppressLint("MissingPermission")
class LocationUtils private constructor(private val mContext: Context) {private var locationManager: LocationManager? = nullprivate var locationProvider: String? = nullprivate var location: Location? = nullprivate val TAG = "LocationUtils -> baibai"private var logStr: String? = null/*** LocationListern监听器* 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器*/private var locationListener: LocationListener = object : LocationListener {/*** 当某个位置提供者的状态发生改变时*/override fun onStatusChanged(provider: String, status: Int, arg2: Bundle) {}/*** 某个设备打开时*/override fun onProviderEnabled(provider: String) {}/*** 某个设备关闭时*/override fun onProviderDisabled(provider: String) {}/*** 手机位置发生变动*/override fun onLocationChanged(location: Location) {location.accuracy//精确度Log.d(TAG, "手动位置发生变化 location ${location == null}")setLog("手动位置发生变化 location ${location == null}")setLocation(location)}}init {getLocation()}private fun getLocation() {//1.获取位置管理器locationManager = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager//2.获取位置提供器,GPS或是NetWorkval providers = locationManager!!.getProviders(true)//如果是这个获得的是 [passive] 一个(返回的是有效的供应商列表)
//        val providers = locationManager!!.allProviders//得到 [passive, gps, network] 三个(返回的是所有的供应商列表)Log.d(TAG, providers.toString())setLog(providers.toString())locationProvider = when {//如果设备rom没有添加相关服务,把这个分支去掉,即选择的是GPS定位providers.contains(LocationManager.NETWORK_PROVIDER) -> {//如果是网络定位(基站或wifi)//baibaiLog.d(TAG, "当前是网络定位")getLog("当前是网络定位")LocationManager.NETWORK_PROVIDER}providers.contains(LocationManager.GPS_PROVIDER) -> {//如果是GPS定位Log.d(TAG, "当前是GPS定位")setLog("当前是GPS定位")LocationManager.GPS_PROVIDER}providers.contains(LocationManager.PASSIVE_PROVIDER) -> {//如果是passive定位(即被动方式,是位置更新监测器)Log.d(TAG, "当前是passive定位")setLog("当前是passive定位")LocationManager.PASSIVE_PROVIDER}else -> {Log.d(TAG, "没有可用的位置提供器")setLog("没有可用的位置提供器")return}}// 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED&& ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return}//3.获取上次的位置,一般第一次运行,此值为nullval location = locationManager!!.getLastKnownLocation(locationProvider)Log.d(TAG, "工具类getLocation里的location是否为空: ${location == null}")setLog("工具类getLocation里的location是否为空: ${location == null}")if (location != null) {setLocation(location)}// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistacelocationManager!!.requestLocationUpdates(locationProvider, 0, 0f, locationListener)}private fun setLocation(location: Location) {this.location = locationval address = "纬度:" + location.latitude + ",  经度:" + location.longitudeLog.d(TAG, address)}/*** 获取经纬度*/fun showLocation(): Location? {return location}/*** 移除定位监听*/fun removeLocationUpdatesListener() {// 需要检查权限,否则编译不过if (Build.VERSION.SDK_INT >= 23 &&ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return}if (locationManager != null) {uniqueInstance = nulllocationManager!!.removeUpdates(locationListener)}logStr = null}/*** 测试log*/private fun setLog(log: String){logStr += log + "\n"
//        return logStr as String}fun getLog(): String{return logStr as String}/*** 静态*/companion object {@SuppressLint("StaticFieldLeak")@Volatileprivate var uniqueInstance: LocationUtils? = null/*** 采用Double CheckLock(DCL)实现单例*/fun getInstance(context: Context): LocationUtils? {if (uniqueInstance == null) {synchronized(LocationUtils::class.java) {if (uniqueInstance == null) {uniqueInstance = LocationUtils(context)}}}return uniqueInstance}}}

3、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"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Buttonandroid:id="@+id/btn_location"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="定位" /><TextViewandroid:id="@+id/tv_info"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="#3f30"android:text="定位信息" /><TextViewandroid:id="@+id/tv_log"android:layout_width="match_parent"android:layout_height="350px" /><Viewandroid:layout_width="match_parent"android:layout_height="2px"android:layout_margin="10px"android:background="#666" /><Buttonandroid:id="@+id/btn_remove"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20px"android:text="移除监听" /><Buttonandroid:id="@+id/btn_permission"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="检查权限" /></LinearLayout>

4、在activity里引用

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.View
import bai.bai.bai.demo.R
import bai.bai.bai.demo.location.LocationUtils
import kotlinx.android.synthetic.main.activity_location.*
import android.widget.Toast/*** 定位界面*/
class LocationActivity : Activity(), View.OnClickListener {private var LOCATION_CODE = 111private var mLocationUtils: LocationUtils? = nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_location)initListener()}private fun initListener() {btn_location.setOnClickListener(this)btn_remove.setOnClickListener(this)btn_permission.setOnClickListener(this)}override fun onClick(v: View?) {when (v!!.id) {R.id.btn_location -> {//定位mLocationUtils = LocationUtils.getInstance(this)val location = mLocationUtils!!.showLocation()tv_log.text = mLocationUtils!!.getLog()if (location != null) {val address = "纬度:" + location.latitude + ",  经度:" + location.longitudetv_info.text = address} else {tv_info.text = "location为空"}}R.id.btn_remove -> {//取消定位监听if (mLocationUtils != null) mLocationUtils!!.removeLocationUpdatesListener()tv_log.text = ""tv_info.text = ""}R.id.btn_permission -> {//检查权限checkPermission()}}}override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {when (requestCode) {LOCATION_CODE -> {if (grantResults.isNotEmpty()&& grantResults[0] == PackageManager.PERMISSION_GRANTED&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {// 权限被用户同意。// 执形我们想要的操作Log.d("baibai", "onRequestPermissionsResult === 弹窗已同意")} else {Log.d("baibai", "onRequestPermissionsResult === 弹窗未同意")// 权限被用户拒绝了。//若是点击了拒绝和不再提醒//关于shouldShowRequestPermissionRationale// 1、当用户第一次被询问是否同意授权的时候,返回false// 2、当之前用户被询问是否授权,点击了false,并且点击了不在询问(第一次询问不会出现“不再询问”的选项),之后便会返回false// 3、当用户被关闭了app的权限,该app不允许授权的时候,返回false// 4、当用户上一次不同意授权,没有点击“不再询问”的时候,下一次返回trueif (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {//提示用户前往设置界面自己打开权限Toast.makeText(this, "请前往设置界面打开权限", Toast.LENGTH_SHORT).show()return}}}}}/*** 获取权限(如果没有开启权限,会弹出对话框,询问是否开启权限)*/private fun checkPermission() {if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {//没有开启权限,请求权限ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), LOCATION_CODE)Log.d("baibai", "permission -- 权限未开启")} else {Log.d("baibai", "permission -- 权限已开启")}}}

自定义工具类-----GPS、网络定位相关推荐

  1. ThinkPHP3验证码、文件上传、缩略图、分页(自定义工具类、session和cookie)

    验证码 TP框架中自带了验证码类 位置:Think/verify.class.php 在LoginController控制器中创建生存验证码的方法 login.html登陆模板中 在LoginCont ...

  2. 自定义工具类:工具类介绍

    自定义工具类 自定义注解 自定义注解 package com.learn.domain.poi;import java.lang.annotation.ElementType; import java ...

  3. 第三次学JAVA再学不好就吃翔(part27)--自定义工具类

    学习笔记,仅供参考 面向对象 自定义工具类中使用静态方法 有的时候,我们需要创建一个自己的工具类,方便工作和学习中使用. 在工具类中,我们要在里面放一些静态的方法,方便我们用类名调用,这时,为了防止有 ...

  4. 【开发随机】JAVA+POI+自定义注解+反射构建自定义工具类实现快捷简便的Excel模板化导出(附demo代码)

    220907更新 项目UAT期间,用户反映了一个问题,数据量稍大的情况下,会出现"从某一行开始,往下所有行设置的字体和字体大小不生效"的BUG. 经过排查,发现原因是:POI的XS ...

  5. python如何设计工具类_Python基础之自定义工具类

    class ListHelper: @staticmethod def find_all(target, func_condition): """ 查找列表中满足条件的所 ...

  6. springboot自定义工具类构建打包踩坑经历

    前言 1.如何打包一个工具类? 2.如何在工具类中引入第三方jar包? 3.如何在调用工具类时能够正确识别工具类中的静态资源? 4.如何在静态方法中注入变量? 如果你有以上问题,请看下去,相信对你有帮 ...

  7. android 定位工具类,高德地图定位工具类

    引言 定位功能初始化设置时耗时较多,如果放在Activity中操作,难免会有Activity切换较慢的问题.通过该工具类,可以实现一次初始化,多处随时调用.具有占用资源少,使用方便,便于复用,速度快, ...

  8. Android获取GPS网络定位经纬度信息

    定位一般分为是:GPS定位,WIFI定位,基站定位 和 AGPS定位 GPS定位 GPS定位需要手机GPS模块硬件支持.GPS走的是卫星通信的通道,在没有网络连接的情况下也能使用,并且通过GPS方式准 ...

  9. java validate校验_自定义工具类实现validate参数校验

    前言 相信项目中做一些htttp接口,避免不了要对参数进行校验,大多数情况下,其实我们只是校验是否为NULL就可以了 1.通过注解实现各种状态的字段 1.1.引入依赖 默认的版本是6.0.9.Fina ...

最新文章

  1. 2017年7个主要的金融行业数据趋势
  2. CentOS7 minimal 安装
  3. bootstrap-table 新增可编辑行_现代Web开发堆栈工具DevExtreme 新增Gantt组件,助力项目管理...
  4. 解决the resource is not on the build path of a java project
  5. 向右挪一个键位使密码好记又安全
  6. vue修改config后怎么生效_梦幻西游 金银锦盒修改后资金怎么攥 可以考虑跑商
  7. 推荐系统系列教程之十七:简单却有效的Bandit算法
  8. sql server 内存_SQL Server内存性能指标–第1部分–内存页/秒和内存页故障/秒
  9. php 连接 sqlserver
  10. @开发者,一文搞懂什么是 C# 计时器!|CSDN 博文精选
  11. 小米武大共建人工智能实验室,先期提供1000万研发经费
  12. 架构设计师—你在哪层楼?
  13. 微软邀请IT管理人员及开发人员参加用户体验在线调研
  14. Python+Android进行TensorFlow开发
  15. php学生签到系统论文,学生签到系统设计与实现.doc
  16. windows系统设置保护视力方法
  17. Android MTP 转载http://www.cnblogs.com/skywang12345/p/3474206.html
  18. 2016年趋势科技夏令营面试题目
  19. 2021-SZTU第一届acm校赛总结
  20. windows 7 下让 Delphi 2010 开发的程序具备UAC管理员权限

热门文章

  1. 正则计算器版中版之最后一版!
  2. html语言中,amp;amp;用来表示,详解HTML5中的amp;amp;lt;templateamp;amp;gt;标签
  3. [Leetcode]5920. 分配给商店的最多商品的最小值
  4. Solidworks钣金展开实例设计视频教程
  5. h5游戏php语言什么意思,我们常说的H5游戏是什么意思?
  6. winform中的状态栏,以及在状态栏目上显示时间
  7. 阿里高层大调整:蒋凡被调离淘宝天猫!
  8. 肽核酸PNA-多肽PNA-TPP|Glt-Ala-Ala-Pro-Leu-pNA|Suc-Ala-Pro-pNA|Suc-AAPL-pNA|Suc-AAPM-pNA
  9. 人脸识别智能锁OTP语音芯片选型指南
  10. C#100分秘籍 sduwh