I am trying to get sensor gyroscope reading from a fragment
I implemented the SensorEventListener
public class Fragment1 extends Fragment implements View.OnClickListener, SensorEventListener
private SensorManager mSensorManager;
private Sensor mSensorGyro;
float [] history = new float[2];
public void onCreate(Bundle savedInstanceState) {
getActivity().getSystemService(Context.SENSOR_SERVICE);
mSensorGyro = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
}
Here's how I handled on incoming sensor readings.
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
Log.d(TAG, "onSensorChanged: ");
switch (sensorEvent.sensor.getType()) {
case Sensor.TYPE_GYROSCOPE:
float xChange = history[0] - sensorEvent.values[0];
float yChange = history[1] - sensorEvent.values[1];
history[0] = sensorEvent.values[0];
history[1] = sensorEvent.values[1];
if (xChange > 2) {
//clockwise
Log.d(TAG, "onSensorChanged: Clockwise");
} else if (xChange < -2) {
//anticlockwise
Log.d(TAG, "onSensorChanged: Anti-Clockwise");
}
if (yChange > 2) {
//forward
Log.d(TAG, "onSensorChanged: Forward");
}
}
}
When I run it on my android device, I am not getting any reading back, judging from the missing log on android logcat.
What could be the issue?
Missing listener register
mSensorManager.registerListener(this, mSensorGyro, SensorManager.SENSOR_DELAY_NORMAL);
Related
I need to get head movements and according to that head turns (rotations). I need to do some work there. This is in case of inserting device in google cardboard.
I have searched the internet but I found no proper information. Please help me out here.
Thanks in advance.
Use Sensor class for this as shown below..
SensorEventListener mSensorListener = new SensorEventListener() {
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if (event.values != null && event.values.length > 1) {
accelDataOld = rawAccelData;
rawAccelData = event.values[1];
tweenStep = (rawAccelData - accelData) / TWEEN_TIMING;
}
} else if (sensor.getType() == Sensor.TYPE_GYROSCOPE) {
if (event.values != null && event.values.length > 1) {
rawGyroData += event.values[0];
}
}
}
};
I am trying to get the azimuth of the users phone when they take a picture. However, when I put the azimuth to the screen just for debugging purposes currently, it always comes back at 0.0. I am new to using Sensors so I am trying to figure this out. My code is
private void dispatchTakePictureIntent() {
double latitude, longitude;
if (mGpsLocationTracker.canGetLocation()) {
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
} else {
latitude = 0;
longitude = 0;
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Toast.makeText(this, "" + latitude + ", " + longitude, Toast.LENGTH_SHORT).show();
getDirection ();
Toast.makeText(this, Float.toString(degree), Toast.LENGTH_SHORT).show();
}
public void getDirection() {
SensorManager mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> mySensors = mySensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if(mySensors.size() > 0){
mySensorManager.registerListener(mySensorEventListener, mySensors.get(0), SensorManager.SENSOR_DELAY_UI);
}
}
/*
DOES NOT WORK. NEED TO FIX
*/
private SensorEventListener mySensorEventListener = new SensorEventListener(){
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float radianValue = Math.round(event.values[0]);
degree = (float) Math.toDegrees(radianValue);
if (degree < 0.0f) {
degree += 360.0f;
}
}
};
public void takePicture (View view) {
dispatchTakePictureIntent();
}
Can anyone help me with what I'm doing wrong
Doesn't the orientation sensor return the angle in degrees? You're assuming radians and converting to degrees. Given that though, it still should't give you 0.
TYPE_ORIENTATION is depreciated and does not give the correct result
if the device is not flat. You need to use TYPE_ACCELEROMETER and TYPE_MAGNETIC_FIELD to obtain the rotation matrix and then call remapCoordinateSystem before calling getOrientation.
I have implemented a snippet code to calculate the Tesla value of the magnetic field. I have tested it recently and I noticed when I am in the bus the value is 24 but when I am outside the value is about 45. I mean the bus is metal so the value should be higher inside of it. Is there any explanation for this strange behaviour?
I appreciate any help.
Code:
public class MainActivity extends ActionBarActivity implements
SensorEventListener {
String telsaString;
private TextView magneticX;
private TextView magneticY;
private TextView magneticZ;
private TextView magneticT;
private SensorManager sensorManager = null;
private long lastUpdate = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Capture magnetic sensor related view elements
magneticX = (TextView) findViewById(R.id.valMag_X);
magneticY = (TextView) findViewById(R.id.valMag_Y);
magneticZ = (TextView) findViewById(R.id.valMag_Z);
magneticT = (TextView) findViewById(R.id.valMag_T);
// Register magnetic sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onPause();
}
#Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
#Override
protected void onResume() {
super.onResume();
// Register magnetic sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
float magX = sensorEvent.values[0];
float magY = sensorEvent.values[1];
float magZ = sensorEvent.values[2];
magneticX.setText(Float.toString(sensorEvent.values[0]));
magneticY.setText(Float.toString(sensorEvent.values[1]));
magneticZ.setText(Float.toString(sensorEvent.values[2]));
int teslaXYZ = (int)(Math.sqrt((magX * magX) + (magY * magY)
+ (magZ * magZ)));
String str = String.valueOf(teslaXYZ);
magneticT.setText(str);
long curTime = System.currentTimeMillis();
if ((curTime - lastUpdate) > 15000) {
lastUpdate = curTime;
try {
JSONObject tesla = new JSONObject();
tesla.put("tesla", teslaXYZ);
//tesla.put("tesla", teslaXYZ);
telsaString = tesla.toString();
new MyAsyncTask().execute(telsaString);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
A vehicle like a bus will contain many metal parts, some of which will be magnetized and have their own magnetic fields. The magnetometer of your device will pick up the superposition of the geomagnetic field and these additional fields and will show bad directions and absolute values compared to when you're standing away from the vehicle.
The engine and electric infrastructure of the car can also cause interference (While testing, I noticed a clear difference in magnetometer readings when starting the engine of my car).
I am trying to send data of the magnetic field sensor to the Server every 5 seconds but I am facing Problem to unregister the sensorListerner from reading data. I have tried it like this sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),1000 * 10); too but without seccuss. Currently the data are being sent to the Server 12 time in one second.
I appreciate any help.
Code:
public class MainActivity extends ActionBarActivity implements
SensorEventListener {
String telsaString;
private TextView magneticX;
private TextView magneticY;
private TextView magneticZ;
private TextView magneticT;
private SensorManager sensorManager = null;
private float magX;
private float magY;
private float magZ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Capture magnetic sensor related view elements
magneticX = (TextView) findViewById(R.id.valMag_X);
magneticY = (TextView) findViewById(R.id.valMag_Y);
magneticZ = (TextView) findViewById(R.id.valMag_Z);
magneticT = (TextView) findViewById(R.id.valMag_T);
// Register magnetic sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
final SensorEventListener listener = this;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sensorManager.unregisterListener(listener);
}
}, 5000);
}
#Override
protected void onPause() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onPause();
}
#Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magX = sensorEvent.values[0];
magY = sensorEvent.values[1];
magZ = sensorEvent.values[2];
magneticX.setText(Float.toString(sensorEvent.values[0]));
magneticY.setText(Float.toString(sensorEvent.values[1]));
magneticZ.setText(Float.toString(sensorEvent.values[2]));
double teslaXYZ = (Math.sqrt((magX * magX) + (magY * magY)
+ (magZ * magZ)));
magneticT.setText(Double.toString(teslaXYZ));
try {
JSONObject tesla = new JSONObject();
tesla.put("tesla", teslaXYZ);
telsaString = tesla.toString();
new MyAsyncTask().execute(telsaString);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Edit:
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
10*1000*1000);
.
.
.
.
long curTime = System.currentTimeMillis();
if ((curTime - lastUpdate) > 10000) {
lastUpdate = curTime;
}
The rate you provided 1000 * 10 is in microseconds, so you are requesting a 10 millisecond update period. Note that the requested sample period is only a request. The rate may be faster or slower, you need to track the times and do the appropriate thing. When you wish to completely stop receiving events, unregister your listener with the SensorManager.unregisterListener() method.
I have made some apps (pedometer, heart rate, audio recorder) for the moto360 with android wear. everything works fine, but I don't know how to save the data on the watch and how to access the data on the smartphone. I have managed to send messages to the watch, but I can't send data from the watch to the phone. I can save my data on the smartphone, but I don't know how to manage it on the smartwatch. can someone show me a tutorial or an example? thank you so much!
edit:
The following Code below is used for tracking the heartrate on the Moto360 and it works fine.
I tried to transfer the data from the watch to the Phone for that I used this tutorial -> https://developer.android.com/training/wearables/data-layer/data-items.html
After implementing the Code from the android page I couldn`t run the Project on the device!
public class MainActivity extends Activity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewStepCount;
private TextView mTextViewStepDetect;
private TextView mTextViewHeart;
PutDataMapRequest dataMap = PutDataMapRequest.create("/count");
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextViewStepCount = (TextView) stub.findViewById(R.id.step_count);
mTextViewStepDetect = (TextView) stub.findViewById(R.id.step_detect);
mTextViewHeart = (TextView) stub.findViewById(R.id.heart);
getStepCount();
}
});
}
private void getStepCount() {
SensorManager mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
Sensor mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
Sensor mStepCountSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
Sensor mStepDetectSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mStepCountSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mStepDetectSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private String currentTimeStr() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(c.getTime());
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int) event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
} else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
String msg = "Count: " + (int) event.values[0];
mTextViewStepCount.setText(msg);
Log.d(TAG, msg);
} else if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
String msg = "Detected at " + currentTimeStr();
mTextViewStepDetect.setText(msg);
Log.d(TAG, msg);
} else {
Log.d(TAG, "Unknown sensor type");
}
}
}
this code helps me a lot, i hope it helps many other people :)
https://github.com/pocmo/SensorDashboard
You need to uses data assets. Image sample:
private static Asset createAssetFromBitmap(Bitmap bitmap) {
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
return Asset.createFromBytes(byteStream.toByteArray());
}
and then
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Asset asset = createAssetFromBitmap(bitmap);
PutDataRequest request = PutDataRequest.create("/image");
request.putAsset("profileImage", asset);
Wearable.DataApi.putDataItem(mGoogleApiClient, request);
more http://developer.android.com/training/wearables/data-layer/assets.html