Android获取当前定位

昨天写了一个获取当前定位的Demo,但发现不能及时获取到定位信息在第一次安装,是因为系统默认有显示通过gps来获取定位,但实际上这样获取一般是第一次会获取不到,所以通过搜索相关资料和文档后来发现应该是按照network再gps这样获取比较靠谱,一般只要开启了定位并且获取到了获取定位的权限一般都能取到定位信息。

1. 首先看一下看一下权限的设置

首先在AndroidManifest.xml文件中配置定位所需要的权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

接下来是权限的判断

private fun checkPermission(context: Context): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(
                        context,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        context,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return false
                }
            }

            return true
        }

权限申请

private fun requestPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
            _requestPermissionCode
        )
    }

权限申请结果的处理

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == _requestPermissionCode) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
               //获取到权限在这里写获取定位的代码
            } else {
                //获取权限失败需要重新获取权限
            }
        }
    }

2. 判断GPS是否开启

open fun isGpsEnabled(context: Context) : Boolean {
            val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            return gps || network
        }

如果没有开启定位选项可以对用户做出相应提示,用户点击可以直接到设置定位选项的Setting里

   private fun tipSettingGPS() {
        AlertDialog.Builder(this).setMessage("请打开GPS").setPositiveButton("确定") { dialog: DialogInterface, _: Int ->
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivityForResult(intent, _settingGPSCode) // 设置完成后返回到原来的界面
        }.setNegativeButton("取消") { dialog:DialogInterface, _:Int ->
            dialog.dismiss()
            finish()
        }.setCancelable(false).show()

    }
0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x