Detect phone flipping

By checking Android's build-in accelerometer sensor status, we can detect the phone flipping (face-up/face-down).

Detect phone flipping

package com.exercise.AndroidDetectFlipping;

import java.util.List;

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 AndroidDetectFlipping extends Activity {

SensorManager sensorManager;
Sensor accelerometerSensor;
boolean accelerometerPresent;

TextView face;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

face = (TextView)findViewById(R.id.face);

sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensorList.size() > 0){
accelerometerPresent = true;
accelerometerSensor = sensorList.get(0);
}
else{
accelerometerPresent = false;
face.setText("No accelerometer present!");
}
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(accelerometerPresent){
sensorManager.registerListener(accelerometerListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}

@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(accelerometerPresent){
sensorManager.unregisterListener(accelerometerListener);
}
}

private SensorEventListener accelerometerListener = new SensorEventListener(){

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
float z_value = arg0.values[2];
if (z_value >= 0){
face.setText("Face UP");
}
else{
face.setText("Face DOWN");
}
}};

}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/face"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>


Download the files.

Related articles:
- Get the list of available sensors, SensorManager.getSensorList()
- Detect Android Accelerometer sensor changed
- Detect Shaking