Detect "natural" orientation of screen, using Display.getRotation()

Detect

package com.AndroidOrientation;

import android.app.Activity;
import android.content.Context;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidOrientation extends Activity{

TextView textOrientation;
MyOrientationEventListener myOrientationEventListener;

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

myOrientationEventListener =
new MyOrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL);

if (myOrientationEventListener.canDetectOrientation()){
myOrientationEventListener.enable();
}else{
Toast.makeText(AndroidOrientation.this,
"Can't Detect Orientation!",
Toast.LENGTH_LONG).show();
}
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myOrientationEventListener.disable();
}

class MyOrientationEventListener extends OrientationEventListener{

String prevOrientation = "";
String curOrientation = "";

public MyOrientationEventListener(Context context, int rate) {
super(context, rate);
// TODO Auto-generated constructor stub
}

@Override
public void onOrientationChanged(int arg0) {
// TODO Auto-generated method stub

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
switch(display.getRotation()){
case(Surface.ROTATION_0):
curOrientation = "ROTATION_0";
break;
case(Surface.ROTATION_90):
curOrientation = "ROTATION_90";
break;
case(Surface.ROTATION_180):
curOrientation = "ROTATION_180";
break;
case(Surface.ROTATION_270):
curOrientation = "ROTATION_270";
break;
}

textOrientation.setText(curOrientation);

if (!curOrientation.equals(prevOrientation)){
Toast.makeText(AndroidOrientation.this, curOrientation, Toast.LENGTH_LONG).show();
prevOrientation = curOrientation;
}
}
}
}


0 Response to "Detect "natural" orientation of screen, using Display.getRotation()"

Posting Komentar