Android 获取当前定位

今天试着写了一个android获取定位的Demo贴上来以便以后查看,其中涉及到定位权限的判断以及获取

package com.lmm.locationdemo

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    private var mLocationManager: LocationManager? = null
    private var mProvider: String? = null
    private val _requestPermissionCode = 1000
    private var mGPSText: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        location()
    }

    private fun initView() {
        mGPSText = findViewById(R.id.gps)
    }

    private fun getLocationManager() {
        if (mLocationManager != null) {
            return
        }
        mLocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    }


    private fun getProvider():String? {
        val criteria = Criteria()
        criteria.accuracy = Criteria.ACCURACY_FINE
        criteria.isSpeedRequired = false
        criteria.isAltitudeRequired = false
        criteria.isBearingRequired = false
        criteria.isCostAllowed = false
        criteria.powerRequirement = Criteria.POWER_LOW
        getLocationManager()
        return mLocationManager?.getBestProvider(criteria, true)
    }

    private fun location() {

        if (!checkPermission()) {

            return
        }

        mProvider = getProvider()

        if (mProvider != null) {
            val location = mLocationManager?.getLastKnownLocation(mProvider!!)
            if (location != null) {
                val gpsStr = "纬度为:" + location!!.latitude + ",经度为:" + location!!.longitude
                mGPSText?.text = gpsStr
            }
            mLocationManager?.requestLocationUpdates(mProvider!!, 2000, 2f, locationListener)
        }
    }

    private val locationListener: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            val gpsStr = "纬度为:" + location.latitude + ",经度为:" + location.longitude
            mGPSText?.text = gpsStr
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
        override fun onProviderEnabled(provider: String) {}
        override fun onProviderDisabled(provider: String) {}
    }

    private fun checkPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermission()
                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) {
                location()
            } else {
                requestPermission()
            }
        }
    }
}

AndroidManifest.xml文件中需要配置如下权限

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

说点什么

avatar
  Subscribe  
提醒