Advertisement

【Android】请求打开蓝牙和定位功能

阅读量:

通常情况下,在用户初次启动应用程序时可能会出现蓝牙广播未被正确接收的情况;这可能与应用程序中的蓝牙配置或设备的地理位置设置未被正确启用有关;因此,在应用程序中添加一个适当的提示信息将有助于提升用户体验。

请求打开定位服务

复制代码
    private fun checkLocationSetting() {
        if (!LocationSetting.isEnabled(this)) {
            runOnUiThread {
                LocationSetting.askToActivate(this)
            }
        }
    }
    
    
      
      
      
      
      
      
      
    
    代码解释
复制代码
    import android.app.AlertDialog
    import android.content.Context
    import android.content.Context.LOCATION_SERVICE
    import android.content.Intent
    import android.location.LocationManager
    import android.os.Build
    import android.provider.Settings
    import android.provider.Settings.SettingNotFoundException
    import android.util.Log
    
    object LocationSetting {
    private val TAG: String = LocationSetting::class.java.simpleName
    
    fun isEnabled(context: Context): Boolean {
        var enabled = false
        try {
            val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager
            enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                locationManager.isLocationEnabled
            } else {
                Settings.Secure.getInt(context.contentResolver,
                    Settings.Secure.LOCATION_MODE) != Settings.Secure.LOCATION_MODE_OFF
            }
        } catch (e: SettingNotFoundException) {
            Log.e(TAG, "Cannot check GPS status: " + e.message, e)
        }
        return enabled
    }
    
    fun askToActivate(context: Context) {
        AlertDialog.Builder(context)
            .setTitle("GPS activation")
            .setMessage("From Android 6, GPS needs to be enabled to find nearby BLE devices.")
            .setCancelable(false)
            .setPositiveButton("Fix") { _, _ ->
                val onGPS = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                context.startActivity(onGPS)
            }
            .show()
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解释

请求打开蓝牙功能

复制代码
    var bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled) {
    // Method1
    //    bluetoothAdapter.enable()
    // Method2
    val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
    startActivity(enableBtIntent)
    }
    
    
      
      
      
      
      
      
      
      
    
    代码解释

全部评论 (0)

还没有任何评论哟~