如何在 Android 的代号 1 中实现本机加速器读出代码?

How to implement native accelerator readout code in Codename 1 for Android?

我正在尝试在代号一中开发本地代码来读取加速度计传感器数据。我在 Android Java 代码中查看了它是如何完成的,在代号一中实现了它,编译没有错误,但它似乎甚至没有通过下面传感器 class 的初始化. sensor.startReading() 方法似乎永远不会被调用。我是否正确实现了加速度计读出本机代码?

下面是我如何调用我的传感器读数 class 方法:

Sensor sensor = (Sensor)NativeLookup.create(Sensor.class);
   if (sensor != null && sensor.isSupported()) {
       sensor.startReading();
}

以下是我实现传感器读数的方式:

package com.pk.sensors;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.content.Context;

public class SensorImpl extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
private float accelX = 0f;
private float accelY = 0f;
private float accelZ = 0f;

public void startReading() {
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

public void onSensorChanged(SensorEvent event) {
    this.accelX = event.values[0];
    this.accelY = event.values[1];
    this.accelZ = event.values[2];
}

public String getAcceleration() {
    return String.valueOf(this.accelX) + " " + 
            String.valueOf(this.accelY) + " " + 
            String.valueOf(this.accelZ);
}

public boolean isSupported() {
    return true;
}

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

这是我实现加速器读出的教程:http://www.techrepublic.com/blog/software-engineer/a-quick-tutorial-on-coding-androids-accelerometer/

不要扩展 Activity,CodenameOne 中有 1 个主 activity,您应该使用它。 像这样获取对 activity 的引用:

android.app.Activity ctx = com.codename1.impl.android.AndroidNativeUtil.getActivity();

然后获取服务:

 mSensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);