简体   繁体   中英

How to detect Android screen orientation changed

Is anyone know how to detect the screen orientation changed before Android invoke onDestroy method? There is an async task in an activity that need to be cancelled when onDestroy method was invoked. I wouldn't want the async task to be cancelled when screen orientation changed.

I dont think that is possible. But I may be wrong. Anyway, look at android:configChanges and the onConfigurationChanged API. That may be of help.

Also, why not cancel the the async task in the onDestroy method?

I can see there is an API which is called during onStop. See isChangingConfigurations . It requires you to be on API version 11 which is Android 3.0

Try this:

int width, height;

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;

You need to add to the manifest android:ConfigChanges. this wont recreate your activity but you will need to manually apply all the resources for the new orientation (if they are changed) by overriding the onConfigurationChanged() method. there you also will have info about the current orientation and some additional params that can change during configuration.

try this

public int getscrOrientation()
{
Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

// Sometimes you may get undefined orientation Value is 0
// simple logic solves the problem compare the screen
// X,Y Co-ordinates and determine the Orientation in such cases
if(orientation==Configuration.ORIENTATION_UNDEFINED){

Configuration config = getResources().getConfiguration();
orientation = config.orientation;

if(orientation==Configuration.ORIENTATION_UNDEFINED){
//if height and widht of screen are equal then
// it is square orientation
if(getOrient.getWidth()==getOrient.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
}else{ //if widht is less than height than it is portrait
if(getOrient.getWidth() < getOrient.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else{ // if it is not any of the above it will defineitly be landscape
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
}
}
return orientation; // return value 1 is portrait and 2 is Landscape Mode
}

I managed to figure out a solution but not sure whether it is correct. When screen orientation changes, Android will invoke onRetainNonConfigurationInstance() method before onDestroy method. We can define a Boolean variable to act as a flag for screen orientation changed. This variable will set to true when onRetainNonConfigurationInstance() method is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM