Enigma
Enigma

Reputation: 351

How to detect if the device has sensor to use compass in Kotlin?

There are some devices that doesn't have built-in sensor to use compass

what i am trying to do here is to navigate or show message to the user if the phone doesn't support this feature

i am trying this:

sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
    sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)
    if (sensor !== null) {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }else{
        val intent = Intent(this, SetProfileActivity::class.java)
        startActivity(intent)
    }

but get this error every time:

sensorManager.getDefault…(Sensor.TYPE_ORIENTATION) must not be null

what am i doing wrong?

Upvotes: 2

Views: 466

Answers (1)

lprend
lprend

Reputation: 152

I just stumbled over the same problem.

This is the solution I found and works for me:

val pm: PackageManager = context.packageManager
if (!pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {
  // This device does not have a compass, turn off the compass feature
}

Upvotes: 1

Related Questions