Skip to content

Instantly share code, notes, and snippets.

@FooBarrior
Last active December 20, 2018 09:43
Show Gist options
  • Save FooBarrior/b8317a7a26b248c8b4161114d594e9cf to your computer and use it in GitHub Desktop.
Save FooBarrior/b8317a7a26b248c8b4161114d594e9cf to your computer and use it in GitHub Desktop.
package com.example.nikit.compass;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import static android.hardware.Sensor.TYPE_MAGNETIC_FIELD;
@SuppressLint("DefaultLocale")
public class MainActivity extends AppCompatActivity
implements SensorEventListener {
void registerSensor(int sensorType)
{
SensorManager senSensorManager =
(SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor =
senSensorManager.getDefaultSensor(
sensorType);
senSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
Bitmap bm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerSensor(Sensor.TYPE_MAGNETIC_FIELD);
registerSensor(Sensor.TYPE_ACCELEROMETER);
bm = BitmapFactory.decodeResource(
getResources(), R.drawable.peka);
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(bm);
}
float [] magnetData = new float[3];
float [] accelerationData = new float[3];
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
magnetData = event.values;
else
accelerationData = event.values;
final TextView text = findViewById(R.id.hello);
float[] rotation = new float[9];
float[] compass = new float[3];
SensorManager.getRotationMatrix(rotation, null,
accelerationData, magnetData);
SensorManager.getOrientation(rotation, compass);
ImageView imageView = findViewById(R.id.imageView);
Bitmap rotatedBitmap = rotateBitmap(bm,
-compass[0] * 180 / 3.141592f);
imageView.setImageBitmap(rotatedBitmap);
text.setText(String.format("%f %f %f",
compass[0], compass[1], compass[2]));
}
public static Bitmap rotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment