get tilt angle Android - 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);
}
}

Related

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

Android Tilting-Mind blowing

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

How to get more than two color when i shake my handheld device.My App is on sensor

Hi my app is on sensors and I am not able to find any other color if i shake it.I have provided only two colors in if else loop. But if in want to add some more colors then what should i add. What is the solution.Please help me in this problem.
package com.sensortestactivity;
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;
// -- CALLED WHEN THE ACTIVITY IS FIRST CREATED --//
#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);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
lastUpdate = System.currentTimeMillis();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// -- MOVEMENT --
float x = values[0];
float y = values[1];
float z = values[2];
float accelerationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelerationSquareRoot >= 2) {
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this, "DEVICE WAS SHUFFELED", Toast.LENGTH_SHORT)
.show();
if (color) {
view.setBackgroundColor(Color.GREEN);
} else {
view.setBackgroundColor(Color.RED);
}
color = !color;
}
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
protected void onResume() {
super.onResume();
// -- REGISTER THIS CLASS AS A LISTENER FOR THE ORIENTATION AND
// ACCELEROMETER SENSORS --
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
}
you may use
view.setBackgroundColor(HEXVALUE);
The hexvalue is used like this: 0xAARRGGBB
AA = alpha channel
RR = red channel
GG = green channel
BB = blue channel
A valid color would be: 0xFFFF0000 which will create red
Another valid color: 0xFFF0F0F0
for hex numbers you should take a look at wikipedia. http://en.wikipedia.org/wiki/Hexadecimal
You can randomly set the color using a random number generator.
Math.random() * 17
This will give you integer values starting with 0 and ending at 16. You just need to calc those to hex:
0 = 0
1 = 1
2 = 2
...
9 = 9
10 = A
11 = B
...
16 = F

Drawing an dynamic arrow pointing to a particular location on earth

I have implemented a program that is able to get the distance and direction of other person. Now I want to show this information by a dynamic arrow pointing to the other person direction (like a needle) and as the user moves his phone, the arrow will change its direction to still point the other person direction.
So, it is to be implemented like this: an activity will pass the direction (of the other person) in degrees (0<= x <=360) to another activity whose task is to graphically show the arrow.
I know how to know the azimuth value and thereby calculate the degree of rotation of arrow for a particular direction value (x). I know the logic of implementation but I have no knowledge about graphic, animation etc.
Any quick Help is highly appreciated.
This is the code which meets the requirement. I dont know but a better solution may exists :-
package com.visd.giraffe;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
public class arrowhandler extends Activity implements SensorEventListener {
Matrix mtx = new Matrix();
ImageView img;
Bitmap bmp ;
int w,h;
float d = 0;
float oldval = 0,currentrot = 0, rotate = 0,senserotat;
private SensorManager sensorManager = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a reference to a SensorManager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.mmmain);
String[] arrs = getIntent().getExtras().getStringArray("SMSR");
int degr = arrs[0].indexOf("Dgr:");
String msgg = "Location of " + arrs[0].substring((arrs[0].indexOf("nosss"))+5) + "\n\n" + arrs[0].substring(0, degr);
Log.d("AOA",arrs[0].substring(degr+4));
d = (Float.valueOf(arrs[0].substring(degr+4, arrs[0].indexOf("nosss")))).floatValue();
Log.d("AOA dv", Float.toString(d));
if (d>0)
{
d = d+180;
}
else if (d<0)
{
d = 180 - (Math.abs(d));
}
Log.d("AOA dv", "2" + Float.toString(d));
Log.d("AOA",Float.toString(d));
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(msgg);
img=(ImageView)findViewById(R.id.imageView1);
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bluearrow);
// Getting width & height of the given image.
w = bmp.getWidth();
h = bmp.getHeight();
}
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
senserotat = d-sensorEvent.values[0];
if (senserotat < 0)
{
senserotat = 360 - (Math.abs(senserotat));
}
rotate = (360-currentrot)+senserotat;
if (rotate>360)
{
rotate = rotate-360;
}
mtx.postRotate(rotate);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, w, h, mtx, true);
BitmapDrawable bmd = new BitmapDrawable(rotatedBMP);
img.setImageDrawable(bmd);
currentrot = senserotat;
//Log.d("TTTT", Float.toString(sensorEvent.values[0]));
}
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
// Register this class as a listener for the accelerometer sensor
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
// ...and the orientation sensor
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
}

Categories

Resources