Android kotlin - 应用程序在检查GPS是否启用时停止

博观而约取,厚积而薄发。这篇文章主要讲述Android kotlin - 应用程序在检查GPS是否启用时停止相关的知识,希望能为你提供帮助。
【Android kotlin - 应用程序在检查GPS是否启用时停止】这是代码:

val gps_enabled = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER)if(!gps_enabled) { Log.d("letsSee", "GPS IS OFF") }else{ Log.d("letsSee", "GPS IS ON") }

当我尝试检查GPS是打开还是关闭时,应用程序崩溃了。一切都工作正常没有检查,但我仍然需要检查它!有任何想法吗?
09-16 03:59:12.533 32454-32454/com.amoflirt.amoflirt E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering 09-16 03:59:13.713 32454-32454/com.amoflirt.amoflirt E/AndroidRuntime: FATAL EXCEPTION: main kotlin.KotlinNullPointerException at com.amoflirt.amoflirt.MainActivity.getLocation(MainActivity.kt:95) at com.amoflirt.amoflirt.MainActivity$onCreate$3.onClick(MainActivity.kt:67) at android.view.View.performClick(View.java:4475) at android.view.View$PerformClick.run(View.java:18786) at android.os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5419) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) at dalvik.system.NativeStart.main(Native Method)

答案确保在访问locationManager之前已经定义了val locationManager by lazy { //however you define it normally }
作为旁注,您可以使用Kotlin lazy init:
qazxswpoi

只有在第一次访问它时才会初始化它,然后在该类的生命周期内保留该实例。

    推荐阅读