locationManager.getBestProvider为API 15返回null(API <23)

时间:2017-10-12 00:10:09

标签: android gps kotlin locationmanager android-5.1.1-lollipop

我已经浏览了有关运行时权限的Android文档,但仍无法找到解决方法,使下面的函数适用于以下API。将提供程序更改为LocationManager.GPS_PROVIDER也会导致运行时错误(请求的提供程序gps)不存在)。我还将targetSDKVersion设置为15,但仍无济于事。

函数(在创建时触发requestPermission)

fun getUserLocation(){
    var myLocation = MyLocationListener()
    var locationManager=getSystemService(LOCATION_SERVICE) as LocationManager
    val criteria = Criteria()
    criteria.accuracy = Criteria.ACCURACY_FINE
    var provider = locationManager.getBestProvider(criteria,true)

    if(provider !=null) {
        locationManager.requestLocationUpdates(provider, 10, 3f, myLocation)
        lblAddress.text=location!!.latitude.toString()
    }

}
private fun requestPermission(){

   if(android.os.Build.VERSION.SDK_INT>=23) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
     ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_CODE)
            return
        }


   }
    getUserLocation()
}

build.gradle文件

   apply plugin: 'com.android.application'

   apply plugin: 'kotlin-android'

   apply plugin: 'kotlin-android-extensions'

   android {
   compileSdkVersion 26
   buildToolsVersion "26.0.2"
   defaultConfig {

    applicationId "com.appName.appName"
    minSdkVersion 15
    targetSdkVersion 15
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
   }

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.google.android.gms:play-services-ads:11.4.2'
implementation 'com.google.android.gms:play-services-location:11.4.2'


   }

0 个答案:

没有答案