Android Tilting-Mind blowing - android

So here is my code if someone be kind enough to help out.
I want the orientation values to be displayed but all I get is 0.0 0.0 0.0 so I dont know whats going on I dont think its my phone becasue it fairly modern (HTC One V)
package ple.x75;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class MainActivity extends Activity
{
private ImageView img;
private SensorManager mSensorManager;
private float[] mAccelerometerReading;
private float[] mMagneticFieldReading;
private float[] mRotationMatrix = new float[16];
private float[] mRemapedRotationMatrix = new float[16];
private float[] mOrientation = new float[3];
// Register the event listener and sensor type.
public void setListners(SensorManager sensorManager, SensorEventListener mEventListener)
{
sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
final Button btn_valider = (Button) findViewById(R.id.button);
final TextView txt1 = (TextView) findViewById(R.id.textView);
final SensorEventListener mEventListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
mAccelerometerReading = event.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
mMagneticFieldReading = event.values.clone();
break;
}
if(mAccelerometerReading != null && mMagneticFieldReading != null &&
SensorManager.getRotationMatrix(mRotationMatrix, null, mAccelerometerReading, mMagneticFieldReading))
{
SensorManager.remapCoordinateSystem(mRotationMatrix,
SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, mRemapedRotationMatrix);
SensorManager.getOrientation(mRemapedRotationMatrix, mOrientation);
}
};
};
setListners(sensorManager, mEventListener);
btn_valider.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(mOrientation != null)
{
final CharSequence test;
test="Results: "+mOrientation[0]+" "+mOrientation[1]+" "+mOrientation[2];
txt1.setText(test);
}
else{
final CharSequence test;
test="Results: Apparently Nothing...";
txt1.setText(test);
}
}
});
}
}

Related

Android Studio error:<identifier> expected

This SensorTestActivity.java in which Android Studio marks R in red:
package szabojanos.accelerometer;
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class SensorTestActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private boolean color = false;
private View view;
private long lastUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = findViewById(R.id.textview);
view.setBackgroundColor(Color.GREEN);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = event.timestamp;
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this, "Az eszköz fel volt rázva", Toast.LENGTH_SHORT)
.show();
if (color) {
view.setBackgroundColor(Color.GREEN);
} else {
view.setBackgroundColor(Color.RED);
}
color = !color;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
And this is android_sensor_test.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
I was following this Tutorial: http://www.vogella.com/tutorials/AndroidSensor/article.html#tutorial-accelerometer
Any help would be appreciated.
Clean-Rebuild Your project at first and then Import R
Basic Syntax
import szabojanos.accelerometer.R;
FYI
Call requestWindowFeature after super.onCreate.
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// Call this after super.onCreate
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
You are missing the .R import. You could auto fix this by going on the red line and press the combination ALT+ENTER and choose import yourpackage.R
import yourpackage.R and if there is any issues in youe xml file please resolve then try to clean and build.

Determine compass direction

I am browsing the internet trying to find something that would be usefull in my Android App.
I have my GPS location and several markers added to Google Map. When I turn around the location arrow is ponting wherever I am facing. My concern is if there is any way to determine on which marker I am pointing at? I have made a picture to clarify this.
I presume I can get compass bearing using getRotationMatrix() method, but how can I determine angle between location and the marker?
Checkout Compass class in this project: https://github.com/iutinvg/compass
I have used it succsesfully in this app: https://play.google.com/store/apps/details?id=com.gps.build
Regards.
UPDATE:
After reading your question again, i have realized that I did not give you enough details for "pointing to marker" part. Please check full class below. To calculate pointing direction, us startBearing and stopBearing methods.
Note that bearing degrees are changing with device rotation in BringMeBack class with setBearingDegrees method. Thats is not what you need, so you just have to remove locationManager and to put static bearing coordinate. And call that method only once.
Extended compass class:
package com.gps.bitlab;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import com.gps.bitlab.fragment.MessageDialogFragment;
import com.gps.bitlab.util.Utility;
public class Compass implements SensorEventListener {
private static final String TAG = "Compass";
private SensorManager sensorManager;
private Sensor gsensor;
private Sensor msensor;
private float[] mGravity = new float[3];
private float[] mGeomagnetic = new float[3];
private float azimuth = 0f;
private float currectAzimuth = 0;
private boolean bearing = false;
private float bearingDegrees = -1;
// compass arrow to rotate
public ImageView arrowView = null;
FragmentActivity activity;
public Compass(FragmentActivity activity) {
this.activity = activity;
sensorManager = (SensorManager) activity.getApplicationContext()
.getSystemService(Context.SENSOR_SERVICE);
gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
public void start() {
boolean deviceSensorCompatible = true;
if(!sensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME))
deviceSensorCompatible = false;
if(!sensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME))
deviceSensorCompatible = false;
if(!deviceSensorCompatible) {
Utility.ShowMessage(activity, activity.getString(R.string.erroroccured), activity.getString(R.string.deviceIncompatible), 1);
stop();
}
}
public void startBearing()
{
bearing = true;
start();
}
public void setBearingDegrees(float bearingDegrees)
{
this.bearingDegrees = bearingDegrees;
}
public void stop() {
sensorManager.unregisterListener(this);
}
public void stopBearing()
{
bearing = false;
stop();
}
private void adjustArrow() {
if (arrowView == null) {
Log.i(TAG, "arrow view is not set");
return;
}
Animation an = new RotateAnimation(-currectAzimuth, -azimuth,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
currectAzimuth = azimuth;
an.setDuration(250);
an.setRepeatCount(0);
an.setFillAfter(true);
arrowView.startAnimation(an);
}
#Override
public void onSensorChanged(SensorEvent event) {
final float alpha = 0.97f;
synchronized (this) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity[0] = alpha * mGravity[0] + (1 - alpha)
* event.values[0];
mGravity[1] = alpha * mGravity[1] + (1 - alpha)
* event.values[1];
mGravity[2] = alpha * mGravity[2] + (1 - alpha)
* event.values[2];
// mGravity = event.values;
// Log.e(TAG, Float.toString(mGravity[0]));
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// mGeomagnetic = event.values;
mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
* event.values[0];
mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
* event.values[1];
mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
* event.values[2];
// Log.e(TAG, Float.toString(event.values[0]));
}
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
// Log.d(TAG, "azimuth (rad): " + azimuth);
azimuth = (float) Math.toDegrees(orientation[0]); // orientation
azimuth = (azimuth + 360) % 360;
if(bearing) {
if(bearingDegrees != -1) {
azimuth -= bearingDegrees;
adjustArrow();
}
}
else
adjustArrow();
// Log.d(TAG, "azimuth (deg): " + azimuth);
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Class that use pointing to location functionality:
package com.gps.bitlab;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.gps.bitlab.R;
import com.gps.bitlab.fragment.OnDialogClickListener;
import com.gps.bitlab.util.Utility;
public class BringMeBack extends ActionBarActivity implements LocationListener, OnDialogClickListener {
LocationManager locMng;
Location location;
double lat;
double lon;
double alt;
String name;
Compass compass;
FrameLayout bearingParentLayout;
LinearLayout BaseLayout;
ImageView arrow;
boolean layoutReplaced = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utility.SetLocalization(this);
setContentView(R.layout.activity_bring_me_back);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getActionBar().setDisplayHomeAsUpEnabled(true);
bearingParentLayout = (FrameLayout)findViewById(R.id.bearingParentLayout);
BaseLayout = Utility.GetLoadingView(getLayoutInflater(), getString(R.string.waitingForLocation));
if(savedInstanceState != null)
{
lat = savedInstanceState.getDouble("lat");
lon = savedInstanceState.getDouble("lon");
alt = savedInstanceState.getDouble("alt");
name = savedInstanceState.getString("name");
}
else {
lat = getIntent().getExtras().getDouble("lat");
lon = getIntent().getExtras().getDouble("lon");
alt = getIntent().getExtras().getDouble("alt");
name = getIntent().getExtras().getString("name");
}
if(name != null && !name.equals(""))
getActionBar().setTitle(name);
locMng = (LocationManager)getSystemService(LOCATION_SERVICE);
location = new Location(LocationManager.GPS_PROVIDER);
location.setLongitude(lon);
location.setLatitude(lat);
location.setAltitude(alt);
arrow = (ImageView)findViewById(R.id.bearingArrow);
compass = new Compass(this);
compass.arrowView = arrow;
arrow.setVisibility(View.GONE);
bearingParentLayout.addView(BaseLayout);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
BringMeBack.this.finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
compass.stopBearing();
locMng.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
compass.startBearing();
RequestLocationUpdates();
}
#Override
public void onLocationChanged(Location currentLocation) {
float bearing = currentLocation.bearingTo(location);
Log.d("Location bearing", String.valueOf(bearing));
compass.setBearingDegrees(bearing);
if(!layoutReplaced) {
bearingParentLayout.removeView(BaseLayout);
arrow.setVisibility(View.VISIBLE);
layoutReplaced = true;
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
Log.d("GPS", "Service enabled");
RequestLocationUpdates();
}
#Override
public void onProviderDisabled(String s) {
locMng.removeUpdates(this);
Utility.ShowMessage(BringMeBack.this, getString(R.string.locationServiceDisabledMessage), getString(R.string.locationServiceDisabled), 0);
}
#Override
public void OnPositiveClick(int key, Object... args) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
#Override
public void OnNegativeClick(int key, Object... args) {
}
private void RequestLocationUpdates()
{
if(!locMng.isProviderEnabled(LocationManager.GPS_PROVIDER))
Utility.ShowMessage(BringMeBack.this, getString(R.string.locationServiceDisabledMessage), getString(R.string.locationServiceDisabled), 0);
else
locMng.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this);
}
}

When I get sensor values combine with opengl in Android, It always be crash

I try using sensor to get raw, pitch and roll values.
But I send the value to Renderer class or GLSurfaceView class
that all will be crash when I run on my smartphone.
I tried use:
Renderer.raw = value[0]; in MainActivity class, or
MainActivity.x = raw; in Renderer class, or
use Function:
void setRaw(float raw){
this.raw = raw;
}
and call function in MainActivity.
all unluck...
this is my code:
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
glView = new MyGLSurfaceView(this);
setContentView(glView);
baccel = false;
bcompass = false;
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
compass = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
#Override
protected void onResume() {
glView.onResume();
mSensorManager.registerListener(this,
accel,
SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this,
compass,
SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
#Override
protected void onPause() {
glView.onPause();
mSensorManager.unregisterListener(this, accel);
mSensorManager.unregisterListener(this, compass);
super.onPause();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
for (int i = 0; i < 3; i++) {
accelValues[i] = event.values[i];
}
baccel = true;
break;
case Sensor.TYPE_MAGNETIC_FIELD:
for (int i = 0; i < 3; i++) {
compassValues[i] = event.values[i];
}
bcompass = true;
break;
}
if (!baccel || !bcompass)
return;
if (SensorManager.getRotationMatrix(rotationMatrix, null, accelValues,
compassValues)) {
SensorManager.remapCoordinateSystem(rotationMatrix,
SensorManager.AXIS_X, SensorManager.AXIS_Z, rotationMatrix);
SensorManager.getOrientation(rotationMatrix, values);
update();
baccel = false;
bcompass = false;
}
}
void update() {
gv.setRaw(values[0]);
gv.setPitch(values[1]);
gv.setRoll(values[2]);
}
}
and in MyGlSurfaceView:
float raw, pitch, roll;
protected void setRaw(float raw){
this.raw = raw;
}
protected void setPitch(float pitch){
this.pitch = pitch;
}
protected void setRoll(float roll){
this.roll = roll;
}
this is my log
Can someone help me?
My init code:
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity implements SensorEventListener {
private GLSurfaceView glView;
SensorManager mSensorManager;
Sensor accel;
Sensor compass;
private MyGLSurfaceView gv;
boolean baccel, bcompass = false;
float[] accelValues = new float[3];
float[] compassValues = new float[3];
float[] rotationMatrix = new float[9];
float[] values = new float[3];
MyGLSurfaceView init:
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.KeyEvent;
import android.view.MotionEvent;
public class MyGLSurfaceView extends GLSurfaceView {
MyGLRenderer mRenderer;
public MyGLSurfaceView(Context context) {
super(context);
mRenderer = new MyGLRenderer(context);
this.setRenderer(mRenderer);
this.requestFocus();
this.setFocusableInTouchMode(true);
}
I don't think you know what is going on here.
When you do private MyGLSurfaceView gv; gv is a null variable. It means that if you don't do something like gv = new ...... it will stay null for the rest of the app cycle. This means that update() will throw NPE.
On another hand you have glView = new MyGLSurfaceView(this);. This suggests me that glView is a MyGLSurfaceView right? So you should define it like private MyGLSurfaceView glView; and not private GLSurfaceView glView; even if MyGLSurfaceView extends GLSurfaceView
So you should use glView since it's the only variable that you're actually defining and instantiating correctly. But do do this, and to use the set angles method you have to change private GLSurfaceView glView to private MyGLSurfaceView glView.
Concluding:
Change private GLSurfaceView glView to private MyGLSurfaceView glView
and
remove gv and use only glView

How to use Android sensors to detect how fast the device is moving

I am a beginner at android programming and I have come up with some progress on getting the sensor data (Source code below). Can someone help me with detecting how fast my Android device is moving using these information? For example if I am moving the device fast, it will give me like 10, and if I am moving it slowly, I will get like 1. Aside from accelerometer, all other sensors are also OK for me.
package course.examples.Sensors.ShowValues;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class SensorRawAccelerometerActivity extends Activity implements
SensorEventListener {
private static final int UPDATE_THRESHOLD = 500;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView mXValueView, mYValueView, mZValueView;
private long mLastUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mXValueView = (TextView) findViewById(R.id.x_value_view);
mYValueView = (TextView) findViewById(R.id.y_value_view);
mZValueView = (TextView) findViewById(R.id.z_value_view);
// Get reference to SensorManager
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get reference to Accelerometer
if (null == (mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)))
finish();
}
// Register listener
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_UI);
mLastUpdate = System.currentTimeMillis();
}
// Unregister listener
#Override
protected void onPause() {
mSensorManager.unregisterListener(this);
super.onPause();
}
// Process new reading
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long actualTime = System.currentTimeMillis();
if (actualTime - mLastUpdate > UPDATE_THRESHOLD) {
mLastUpdate = actualTime;
float x = event.values[0], y = event.values[1], z = event.values[2];
mXValueView.setText(String.valueOf(x));
mYValueView.setText(String.valueOf(y));
mZValueView.setText(String.valueOf(z));
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// N/A
}
}
Accelerometers measure change in speed (acceleration), not speed itself. If you are looking for short distances you are out of luck. Long distances you can poll this data from the GPS which gives you a heading and average velocity.

get tilt angle Android

I'm trying to get the tilt angle, roll angle from my sensors from my android phone but with no success so far,
when I click on my button which should give me the 3 angles, I get "results: 0.0 -0.0 -0.0"
package com.example;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class MyActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final float[] mValuesMagnet = new float[3];
final float[] mValuesAccel = new float[3];
final float[] mValuesOrientation = new float[3];
final float[] mRotationMatrix = new float[9];
final Button btn_valider = (Button) findViewById(R.id.btn1);
final TextView txt1 = (TextView) findViewById(R.id.textView1);
final SensorEventListener mEventListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// Handle the events for which we registered
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mValuesAccel, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mValuesMagnet, 0, 3);
break;
}
};
};
btn_valider.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);
final CharSequence test;
test = "results: " + mValuesOrientation[0] +" "+mValuesOrientation[1]+ " "+ mValuesOrientation[2];
txt1.setText(test);
}
});
}
}
Your almost there with the code Mike, but to enable the data to be retrieved by the event listener for any of the sensors, the event listener and sensor wanted must be registered with the SensorManager class using:
SensorManager _sensorManager;
_sensorManager.registerListener(mEventListener, _sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
Below is your code adapted to show the data that I believe is what you want to see.
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class StackOverflowTestingGroundActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
final float[] mValuesMagnet = new float[3];
final float[] mValuesAccel = new float[3];
final float[] mValuesOrientation = new float[3];
final float[] mRotationMatrix = new float[9];
final Button btn_valider = (Button) findViewById(R.id.btn1);
final TextView txt1 = (TextView) findViewById(R.id.textView1);
final SensorEventListener mEventListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// Handle the events for which we registered
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mValuesAccel, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mValuesMagnet, 0, 3);
break;
}
};
};
// You have set the event lisetner up, now just need to register this with the
// sensor manager along with the sensor wanted.
setListners(sensorManager, mEventListener);
btn_valider.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);
final CharSequence test;
test = "results: " + mValuesOrientation[0] +" "+mValuesOrientation[1]+ " "+ mValuesOrientation[2];
txt1.setText(test);
}
});
}
// Register the event listener and sensor type.
public void setListners(SensorManager sensorManager, SensorEventListener mEventListener)
{
sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
}

Categories

Resources