使用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
    }
}

代碼拙略,請指教!

相關文章
相關標籤/搜索