简体   繁体   中英

Kotlin/Native access device sensor in Android specific part

I'm currently stuck on a task that i thought is quite basic. I\\m developing a library in Kotlin/Native that should query the gravity sensor in iOS and Android.

Almost all the logic is in the common part and just the communication with the devices sensor is implemented in the platform specific methods. Surprisingly all the iOS core libraries (CoreMotion in this case) have been ported so that the implementation was quite easy.

CoreMotion in this case allows me to add a listener on the gravity sensor which is calling a callback whenever the orientation of the screen changes with respect to X, Y or Z (I'm interested in Z btw)

In Android I'd do something like this

private lateinit var sensorManager: SensorManager

fun setupSensor() {

    this.sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager

    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.let {
        this.accelerometer = it
    }
    sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY)?.let {
        this.gravity = it
    } 

}

But the imports needed are not available in Kotlin/Native

import android.hardware.Sensor;
import android.hardware.SensorManager;

Is there a way to access this kind of hardware (the gravity sensor) in Kotlin/Native? Or better in the Android specific part of Kotlin/Native?

If you really want it as Kotlin/Native library on Android - it will have direct access to Android NDK, not SDK.

So for sensors it can use functions from https://android.googlesource.com/platform/frameworks/native/+/jb-dev/include/android/sensor.h

In Kotlin/Native these functions available in package platform.android.*

But if all you want is just make your library available in both iOS and Android - much simpler and common way is compile same sources by Kotlin/Native to iOS and by regular Kotlin to Android, using "kotlin-multiplatform" gradle plugin.

I think it would be something like;

 val sensorManager: SensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager

            sensorManager.registerListener(object : SensorEventListener {
                override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
                    //Not needed
                }

                override fun onSensorChanged(event: SensorEvent?) {
                    if (event?.sensor?.type == Sensor.TYPE_GRAVITY) {
                        System.out.println("X: " + event.values[0])
                        System.out.println("Y: " + event.values[1])
                        System.out.println("Z: " + event.values[2])
                    }
                }
            }, sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY), Sensor.TYPE_GRAVITY)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM