使用kotlin在android下获取位置

14年毕业一直从事delphi桌面开发,尝试着去转android,google发布了官方开发语言,以为是一个机会,因此尝试使用kotlin开发,在获取位置信息的时候遇到了一下问题,先记录以下,以便之后查阅。html

参考资料:android

1.探索android6.0的权限模型 http://blog.csdn.net/u014254481/article/details/50338237网络

2.Android M 新的运行时权限开发者须要知道的一切,android开发者app

http://www.android100.org/html/201509/01/178112.html异步

3.android中经过GPS或NetWork获取当前位置的经纬度ide

http://blog.csdn.net/cjjky/article/details/6557561 ui

权限模型

以前在旧的权限模型下用户在安装app时就不得不去授予应用各类各样的权限,而这个app甚至都尚未被使用过。这也就意味着用户必须在使用某个app以前,就对它持有某种程度的信任,而对于不少用户来讲,这可能会直接影响到他们决定是否要安装这个应用程序。 在Android-M中,权限请求列表会大大缩减,并且只会出如今当它们是必需之时。this

权限限制被整理成了八个不一样的权限组:google

在Android-M中,若是是同属于一类的权限,就会被整理到一个组别之下,这个组别将会在用户发出确切请求时来申请得到具体的权限,因此举例来讲,若是要得到“读取日历”(READ_CALENDAR)的权限,那用户就会被提示是否授予“日历”权限。spa

这些权限组别中,不少都包含了好几个具体权限,可表现为如下分组:

                             每一个权限组包含不少具体权限

运行时的权限模型以下:

                                          系统须要作一系列检查来容许你或者用户继续操做

 

下面简单粗暴上代码:

class MainActivity : AppCompatActivity() {
    //lateinit 延后初始化,定义了只能在onCreate中初始化的全局变量
    private lateinit var textView: TextView
    private lateinit var locationManager: LocationManager

    //定义一个权限COde,用来识别Location权限
    private val LOCATION_PERMISSION = 1

    //使用匿名内部类建立了LocationListener的实例
    val locationListener = object : LocationListener {
        override fun onProviderDisabled(provider: String?) {
            toast("关闭了GPS")
            textView.text = "关闭了GPS"
        }

        override fun onProviderEnabled(provider: String?) {
            toast("打开了GPS")
            showLocation(textView, locationManager)
        }

        override fun onLocationChanged(location: Location?) {
            toast("变化了")
            showLocation(textView, locationManager)
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }
    }

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

        //lateinit的变量进行初始化
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        textView = find(R.id.text)

        //若是手机的SDK版本使用新的权限模型,检查是否得到了位置权限,若是没有就申请位置权限,若是有权限就刷新位置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val hasLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
                //requestPermissions是异步执行的
                requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
                        LOCATION_PERMISSION)
            }
            else {
                showLocation(textView, locationManager)
            }
        }
        else {
            showLocation(textView, locationManager)
        }
    }

    override fun onPause() {
        super.onPause()
        val hasLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
        if ((locationManager != null) && ((hasLocationPermission == PackageManager.PERMISSION_GRANTED))) {
            locationManager.removeUpdates(locationListener)
        }
    }

    override fun onResume() {
        //挂上LocationListener, 在状态变化时刷新位置显示,由于requestPermissionss是异步执行的,因此要先确认是否有权限
        super.onResume()
        val hasLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
        if ((locationManager != null) && ((hasLocationPermission == PackageManager.PERMISSION_GRANTED))) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0F, locationListener)
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000,0F, locationListener)
            showLocation(textView, locationManager)
        }
    }

    //申请下位置权限后,要刷新位置信息
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                toast("获取了位置权限")
                showLocation(textView, locationManager)
            }
        }
    }

    fun showLocation(textView: TextView, locationManager: LocationManager) {
        textView.text = getLocation(locationManager).toString()
    }
    
    //获取位置信息
    fun getLocation(locationManager: LocationManager): Location? {
        var location: Location? = null
        if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
            toast("没有位置权限")
        }
        else if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            toast("没有打开GPS")
        }
        else {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
            if (location == null) {
                toast("位置信息为空")
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                if (location == null) {
                    toast("网络位置信息也为空")
                }
                else {
                    toast("当前使用网络位置")
                }
            }
        }
        return location
    }
}

代码拙略,请指教!

相关文章
相关标签/搜索