Hello i am in desperate need of help on this i have an image of a steering and i want to rotate it when the phone is tilted left or right. My app is in landscape mode. You should see the code below. The problem is that the bitmap does not rotate and redraws on different position. I am unable to find the problem.
public class Accelerometer extends Activity {
mySteering steering = null;
private static SensorManager mySensorManager;
private boolean sensorrunning;
public float y;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
steering = new mySteering(this);
setContentView(steering);
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_NORMAL);
sensorrunning = true;
Toast.makeText(this, "Start ORIENTATION Sensor", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "No ORIENTATION Sensor", Toast.LENGTH_LONG).show();
sensorrunning = false;
finish();
}
}
private SensorEventListener mySensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
y = event.values[1];
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(sensorrunning){
mySensorManager.unregisterListener(mySensorEventListener);
Toast.makeText(Accelerometer.this, "unregisterListener", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
public class mySteering extends View {
static final int width = 50;
static final int height = 50;
Accelerometer sensor = new Accelerometer();
Matrix rot = new Matrix();
public mySteering(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.steering);
Paint p = new Paint(); // set some paint options
p.setColor(Color.WHITE);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int centreX = (canvasWidth) / 2;
int centreY = (canvasHeight) / 2;
canvas.drawText("This is on Y " + sensor.y, 5, 40, p);
if (sensor.y <= 12.0 && sensor.y >= -12.0) {
canvas.drawBitmap(bmp, centreX, centreY, null);
invalidate();
}
if (sensor.y > 20.0 && sensor.y < 0.0) {
rot.setRotate(45, centreX, centreY);
canvas.drawBitmap(bmp, rot, p);
invalidate();
}
if (sensor.y < -20.0 && sensor.y > 0.0 ) {
rot.setRotate(-45, centreX, centreY);
canvas.drawBitmap(bmp, rot, p);
invalidate();
}
Can some one figure out or alter the mistakes in the code? Thanks in advance. This is how it looks this time is not rotating or not even redrawn.