If the user turns on the screen rotation in the settings, the Android handles the portrait and the screen switch, the usual practice is to define android:configchanges= "in Androidmanifest.xml" orientation| Keyboardhidden, and then rewrite the Onorientationchanged method, as follows:
if (This.getresources (). GetConfiguration (). Orientation = = Configuration.orientation_landscape) { log.i ("info", "Landscape"); Flat screen} else if (This.getresources (). GetConfiguration (). Orientation = = configuration.orientation_portrait) { log.i ("Info", "Portrait"); Vertical screen}
If the user disables the screen rotation in the settings, how to get the direction of the phone in the app? We can use the Orientationeventlistener (directional event listener), which is an auxiliary class that receives notifications from the Sensormanager (sensor manager) when the direction changes.
Use the following:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {Malbumorientationeventlistener = new Albumorientationeventlistener (this, sensormanager.sensor_delay_normal); if ( Malbumorientationeventlistener.candetectorientation ()) {malbumorientationeventlistener.enable ();} else {Log.d (" Chengcj1 "," Can ' t Detect Orientation ");}} @Overrideprotected void OnDestroy () {malbumorientationeventlistener.disable (); Super.ondestroy ();} Private class Albumorientationeventlistener extends Orientationeventlistener {public Albumorientationeventlistener ( Context context) {super (context);} Public Albumorientationeventlistener (Context context, int.) {Super (context, rate);} @Overridepublic void onorientationchanged (int orientation) {if (orientation = = Orientationeventlistener.orientation_ UNKNOWN) {return;} Guaranteed return only four directions int neworientation = ((orientation + +)/360if (neworientation! = morientation) {morientation = NE The morientation returned by worientation;//is the phone's direction, which is 0°, 90°, 180°, and one of the 270°}}}
Note: As long as the phone offset a little, the direction of change, onorientationchanged will always be executed, but in the actual development, we only care about 4 directions (0°,90°,180°,270°), so use the above method to convert, The principle of conversion is: when the offset angle is less than 45 °, are treated as 0°, greater than 45 °, less than 90 °, are treated as 90°; Similarly, greater than 90 °, less than 135 °, treated as 90°, more than 135 °, less than 180 °, are treated as 180°, and so on ...
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Get phone direction