androidcodenameoneaccelerator

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


I am trying to develop a native code in Codename One to read out the accelerometer sensor data. I looked up how it's done in Android Java code, implemented it in Codename One, compiled without errors, but it doesn't seem to even get pass the initialization of the sensor class below. The method sensor.startReading() seems never to be called. Did I implement the accelerometer readout native code correctly?

Here is how I call my sensor readout class method:

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

Here is how I implement the sensor readout:

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) {
}

This is the tutorial I implemented the accelerator readout from: http://www.techrepublic.com/blog/software-engineer/a-quick-tutorial-on-coding-androids-accelerometer/


Solution

  • Don't extend an Activity, in CodenameOne there is 1 main activity and you should use that. Get a reference to that activity like this:

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

    Then get the service:

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