AccelerationProviderImpl.java
/*
* Copyright © 2012 Nokia Corporation. All rights reserved.
* Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
* Oracle and Java are trademarks or registered trademarks of Oracle and/or its
* affiliates. Other product and company names mentioned herein may be trademarks
* or trade names of their respective owners.
* See LICENSE.TXT for license information.
*/
package com.nokia.example.racer.sensor;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.sensor.ChannelInfo;
import javax.microedition.sensor.Data;
import javax.microedition.sensor.DataListener;
import javax.microedition.sensor.SensorConnection;
import javax.microedition.sensor.SensorInfo;
import javax.microedition.sensor.SensorManager;
class AccelerationProviderImpl
extends AccelerationProvider
implements DataListener {
private SensorConnection sensor;
private int dataType;
/**
* AccelerationProviderImpl constructor. Opens connection to the acceleration sensor.
*
* @throws IOException
*/
public AccelerationProviderImpl()
throws IOException {
SensorInfo infos[] = SensorManager.findSensors("acceleration", null);
if (infos.length > 0) {
dataType = infos[0].getChannelInfos()[0].getDataType();
try {
sensor = (SensorConnection) Connector.open(infos[0].getUrl());
sensor.setDataListener(this, 1);
}
catch (SecurityException se) {
throw new IOException("could not open sensor");
}
catch (IOException ioe) {
throw new IOException("could not open sensor");
}
catch (IllegalArgumentException iae) {
throw new IOException("could not open sensor");
}
}
else {
throw new IOException("acceleration sensor not found");
}
}
/**
* Closes the sensor connection.
*/
public void close() {
if (sensor != null) {
sensor.removeDataListener();
try {
sensor.close();
sensor = null;
}
catch (IOException ioe) {
}
}
}
/**
* A method that is called when new sensor data has been received. Delegates data forward.
*
* @param sc
* @param datas Contains sensor data (x, y, z)
* @param bln
*/
public void dataReceived(SensorConnection sc, Data[] datas, boolean bln) {
switch (dataType) {
case ChannelInfo.TYPE_DOUBLE:
final double[] data0 = datas[0].getDoubleValues();
final double[] data1 = datas[1].getDoubleValues();
final double[] data2 = datas[2].getDoubleValues();
dataReceived(data0[data0.length - 1],
data1[data1.length - 1],
data2[data2.length - 1]);
break;
default:
break;
}
}
}