java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
Asked Answered
T

37

258

I am facing the problem while retrieving the contacts from the contact book in Android 8.0 Oreo java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I am trying to get the contact in my activity from the phone contact book and it works perfect for Lollipop, Marshmallow, Nougat, etc but it will gives me the error for Oreo like this please help me. My code is here below.

Demo Code :-

private void loadContacts() {
            contactAsync = new ContactLoaderAsync();
            contactAsync.execute();
        }

        private class ContactLoaderAsync extends AsyncTask<Void, Void, Void> {
            private Cursor numCursor;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                Uri numContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                String[] numProjection = new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE};
                if (android.os.Build.VERSION.SDK_INT < 11) {
                    numCursor = InviteByContactActivity.this.managedQuery(numContacts, numProjection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
                } else {
                    CursorLoader cursorLoader = new CursorLoader(InviteByContactActivity.this, numContacts, numProjection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
                    numCursor = cursorLoader.loadInBackground();
                }

            }

            @Override
            protected Void doInBackground(Void... params) {
                if (numCursor.moveToFirst()) {
                    try {
                        final int contactIdIndex = numCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
                        final int displayNameIndex = numCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                        final int numberIndex = numCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        final int typeIndex = numCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                        String displayName, number, type;
                        do {
                            displayName = numCursor.getString(displayNameIndex);
                            number = numCursor.getString(numberIndex);
                            type = getContactTypeString(numCursor.getString(typeIndex), true);
                            final ContactModel contact = new ContactModel(displayName, type, number);
                            phoneNumber = number.replaceAll(" ", "").replaceAll("\\(", "").replaceAll("\\)", "").replaceAll("-", "");

                            if (phoneNumber != null || displayName != null) {
                                contacts.add(phoneNumber);
                                contactsName.add(displayName);
                                contactsChecked.add(false);

                                filterdNames.add(phoneNumber);
                                filterdContactNames.add(displayName);
                                filterdCheckedNames.add(false);
                            }
                        } while (numCursor.moveToNext());
                    } finally {
                        numCursor.close();
                    }
                }


                Collections.sort(contacts, new Comparator<String>() {
                    @Override
                    public int compare(String lhs, String rhs) {
                        return lhs.compareToIgnoreCase(rhs);
                    }
                });

                InviteByContactActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mContactAdapter.notifyDataSetChanged();
                    }
                });

                return null;
            }
        }

        private String getContactTypeString(String typeNum, boolean isPhone) {
            String type = PHONE_TYPES.get(typeNum);
            if (type == null)
                return "other";
            return type;
        }

        static HashMap<String, String> PHONE_TYPES = new HashMap<String, String>();

        static {
            PHONE_TYPES.put(ContactsContract.CommonDataKinds.Phone.TYPE_HOME + "", "home");
            PHONE_TYPES.put(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE + "", "mobile");
            PHONE_TYPES.put(ContactsContract.CommonDataKinds.Phone.TYPE_WORK + "", "work");
        }
}

Error Log:-

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example, PID: 6573
                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.Activity.InviteByContactActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
                                                              Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
Trefoil answered 3/1, 2018 at 6:41 Comment(8)
Check this: #6746297Human
this may help you #46981197Cervix
check this as well :#46981197Human
Tried all suggestion but no one is worked for me.Trefoil
are you using android:screenOrientation="portrait" in manifest?Featureless
yes i have already set it portrait.Trefoil
i solved it in my project like this https://mcmap.net/q/111253/-facebook-android-only-fullscreen-opaque-activities-can-request-orientationKruller
@ShubhamSejpal did you solved? If not, have you extended a NoActionBar theme putting window translucent and are you compiling with compileSdkVersion = targetSdkVersion = 27Vulgarian
L
72

The problem seems to be happening when your target sdk is 28. So after trying out many options finally this worked.

<activity
            android:name=".activities.FilterActivity"
            android:theme="@style/Transparent"
            android:windowSoftInputMode="stateHidden|adjustResize" />

style:-

<style name="Transparent" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="android:windowIsTranslucent">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
     <item name="android:windowIsFloating">true</item>
     <item name="android:windowContentOverlay">@null</item>
     <item name="android:windowNoTitle">true</item>
     <item name="android:backgroundDimEnabled">false</item>
 </style>

Note:parent="Theme.AppCompat.Light.NoActionBar" is needed for api 28. Previously had something else at api 26. Was working great but started to give problem at 28. Hope it helps someone out here. EDIT: For some only by setting <item name="android:windowIsTranslucent">false</item> and <item name="android:windowIsFloating">false</item> worked.May be depends upon the way you implement the solution works.In my case it worked by setting them to true.

Lehmbruck answered 24/10, 2018 at 8:50 Comment(5)
To anyone else who stumbles upon this "fix" I had to set <item name="android:windowIsTranslucent">false</item> and also had to set <item name="android:windowIsFloating">false</item> before it would work.Welborn
Where exactly is the solution to this? There is no screenOrientation attribute in the activity tag, and the only thing that causes the crash is screenOrientation being set while android:windowIsTranslucent is set to true.Vandenberg
This does not work, unless comments above is used. See answer by Radesh, which covers comments above, and more, and is clearInordinate
Setting translucent to false work for me <item name="android:windowIsTranslucent">false</item>Gibun
In my case, the solution was to remove 'android:theme' from the Activity in AndroidManifest.xml. But if you need it, you can add it programmatically before 'super.onCreate': setTheme(R.style.Theme_AppCompat_Light_Dialog);Clough
W
209

In android Oreo (API 26) you can not change orientation for Activity that have below line(s) in style

 <item name="android:windowIsTranslucent">true</item>

or

 <item name="android:windowIsFloating">true</item>

You have several way to solving this :

1) You can simply remove above line(s) (or turn it to false) and your app works fine.

2) Or you can first remove below line from manifest for that activity

android:screenOrientation="portrait"

Then you must add this line to your activity (in onCreate())

'>=' change to '!=' thanks to Entreco comment

    //android O fix bug orientation
    if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

3) You can create new styles.xml in values-v26 folder and add this to your style.xml. (Thanks to AbdelHady comment)

 <item name="android:windowIsTranslucent">false</item>
 <item name="android:windowIsFloating">false</item>
Wavemeter answered 13/6, 2018 at 8:22 Comment(5)
on Android PIE this works as expected. So the check really should be: android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.OMaximinamaximize
@avisper could you please share full condition codeHayseed
In a device/emulator running API 26, option 2 doesn't work, I had to make a new styles.xml in values-v26 to disable android:windowIsTranslucent for that API only.Renfrew
@Renfrew Good solution, i will add it to my answer but check you code and fine why option 2 doesn't work, that my suggested option,Wavemeter
I used option 3 with a boolean value <bool name="allowWindowFullScreenTranslucent">true</bool> and referred to it in <item name="android:windowIsTranslucent">@bool/allowWindowFullScreenTranslucent</item>. Then in styles.xml under values-v26 set it to false and in values and values-v27 set it to true.Slangy
F
96

In Android O and later this error happens when you set

 android:screenOrientation="portrait"

in Manifest.

Remove that line and use

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

in your activity.

This will fix your issue.

Featureless answered 3/1, 2018 at 7:5 Comment(16)
Any idea why? I want to restrict my app to go into landscape.Stackhouse
Its a bug from google side. Should be fixed in future updates. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); will restrict your app from going into landscape. Make sure you use this in on create of all your activities.Featureless
Removing <item name="android:windowIsTranslucent">true</item> from my style that inherits from Theme.AppCompat.Light.NoActionBar worked for me.Vulgarian
Then the issue becomes: Only fullscreen activities can request orientation. However, I have set the theme of activity to @android:style/Theme.Translucent.NoTitleBar.FullscreenCampfire
This solution works, but it messes up my splashScreenTheme. Shame on Google for frequent sloppy roll-outs...Tergiversate
it does not look like this is a bug but intended : github.com/aosp-mirror/platform_frameworks_base/commit/…Romaineromains
"Intended" to break apps that worked on earlier versions? That goal has been definitely achieved. At least we have a solution, thanks to @RageshSymbolic
@OlegGryb Took me a long time to figure this out. Glad its of help to fellow developpersFeatureless
Many thanks again to @Ragesh. I got a number of crash reports for 8.0 at play console and would never figure it out without his answer. I wish, I could give him more than +1 :)Symbolic
Thanks :) I mistakenly placed that android:screenOrientation="portrait" in my FacebookActivity tag, after removing, it got resolvedInconsiderate
Replacing the manifest attribute by setting the orientation on the Activity class does not solve the problem.Europium
@Europium are you using interstitial ads?Featureless
No @RageshRamesh, I have a regular and simple translucent activity. And it crashes on Android 8.0 (fixed on 8.1) either by setting orientation on the manifest or on the Activity's onCreate methodEuropium
anyone found the solutionInterface
I'm getting this error with 'com.google.firebase:firebase-ads:15.0.1' gradle configuration. I'm updating it to 16.0.1 . I hope it will fix the error. Btw error happens only Android 8. Also firebase crash gives the following line in the crash report: 'na.onTransact(:com.google.android.gms.dynamite_adsdynamite@[email protected] (040408-211705629):10)'Remunerative
@RageshRamesh, I get this error when I try to set orientation programmatically java.lang.IllegalStateException: Only fullscreen activities can request orientationCirsoid
E
86

Google throws this exception on Activity's onCreate method after v27, their meaning is : if an Activity is translucent or floating, its orientation should be relied on parent(background) Activity, can't make decision on itself.

Even if you remove android:screenOrientation="portrait" from the floating or translucent Activity but fix orientation on its parent(background) Activity, it is still fixed by the parent, I have tested already.

One special situation : if you make translucent on a launcher Activity, it has't parent(background), so always rotate with device. Want to fix it, you have to take another way to replace <item name="android:windowIsTranslucent">true</item> style.

Ember answered 19/2, 2018 at 18:3 Comment(5)
I don't have this issue on my OnePlus running Android PIE. So it's not after v27, but when v!=28Maximinamaximize
Do you happen to have a link to the documentation for this ? I can't seem to find it.Wantage
translucent problem is really crazy, thanks ,it fixes my problemChristenson
Thank you for noting that last section 'One special situation...'Christianize
This should be the accepted answer. Makes perfect sense!Geanticline
L
72

The problem seems to be happening when your target sdk is 28. So after trying out many options finally this worked.

<activity
            android:name=".activities.FilterActivity"
            android:theme="@style/Transparent"
            android:windowSoftInputMode="stateHidden|adjustResize" />

style:-

<style name="Transparent" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="android:windowIsTranslucent">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
     <item name="android:windowIsFloating">true</item>
     <item name="android:windowContentOverlay">@null</item>
     <item name="android:windowNoTitle">true</item>
     <item name="android:backgroundDimEnabled">false</item>
 </style>

Note:parent="Theme.AppCompat.Light.NoActionBar" is needed for api 28. Previously had something else at api 26. Was working great but started to give problem at 28. Hope it helps someone out here. EDIT: For some only by setting <item name="android:windowIsTranslucent">false</item> and <item name="android:windowIsFloating">false</item> worked.May be depends upon the way you implement the solution works.In my case it worked by setting them to true.

Lehmbruck answered 24/10, 2018 at 8:50 Comment(5)
To anyone else who stumbles upon this "fix" I had to set <item name="android:windowIsTranslucent">false</item> and also had to set <item name="android:windowIsFloating">false</item> before it would work.Welborn
Where exactly is the solution to this? There is no screenOrientation attribute in the activity tag, and the only thing that causes the crash is screenOrientation being set while android:windowIsTranslucent is set to true.Vandenberg
This does not work, unless comments above is used. See answer by Radesh, which covers comments above, and more, and is clearInordinate
Setting translucent to false work for me <item name="android:windowIsTranslucent">false</item>Gibun
In my case, the solution was to remove 'android:theme' from the Activity in AndroidManifest.xml. But if you need it, you can add it programmatically before 'super.onCreate': setTheme(R.style.Theme_AppCompat_Light_Dialog);Clough
M
34

If you use a fullscreen transparent activity, there is no need to specify the orientation lock on the activity. It will take the configuration settings of the parent activity. So if the parent activity has in the manifest:

android:screenOrientation="portrait"

your translucent activity will have the same orientation lock: portrait.

Mook answered 5/6, 2018 at 7:21 Comment(4)
I think you made a small typo: should be "if you use a fullscreen translucent activity it will take the configuration setting of its parent activity" ^^Gastrectomy
What if my transparent activity is my launcher activity(i.e. splash screen)Clockwork
Is this true for all android versions? Or is it only Android O and upwards?Basophil
This won't work if this is the only Activity that's being used, though (example: starting it from a Service)Vandenberg
D
33

I used android:screenOrientation="behind" instead of android:screenOrientation="portrait". Basically, you created a dialog (in an activity) and dialog can't request orientation by itself it needs parent activity to do this (because a parent is visible in the background and has own layout).

"behind" The same orientation as the activity that's immediately beneath it in the activity stack.

Dystopia answered 20/9, 2018 at 13:15 Comment(1)
What if I want the Activity that I've created to be transparent, showing what's beneath it (including other apps), while also staying on the current orientation? If I let it stay "behind", it can still change orientation on various cases...Vandenberg
T
22

If you have to use setRequestedOrientation(), there is no way but sacrifice the windowIsTranslucent attribute on Android 8.0

values\styles.xml for api level 25- (<8.0)

<style name="Base.Theme.DesignDemo" parent="Base.Theme.AppCompat.Light">
        ...
        <item name="android:windowIsTranslucent">true</item>
        ...
    </style>

values-v26\styles.xml for api level 26 (=8.0)

<style name="Base.Theme.DesignDemo" parent="Base.Theme.AppCompat.Light">
    ...
    <!-- android 8.0(api26),Only fullscreen opaque activities can request orientation -->
    <item name="android:windowIsTranslucent">false</item>
    ...
</style>

values-v27\styles.xml for api level 27+ (>8.0)

<style name="Base.Theme.DesignDemo" parent="Base.Theme.AppCompat.Light">
    ...
    <item name="android:windowIsTranslucent">true</item>
    ...
</style>
Top answered 10/12, 2018 at 6:24 Comment(0)
Q
21

The only solution that really works :

Change:

<item name="android:windowIsTranslucent">true</item>

to:

<item name="android:windowIsTranslucent">false</item>

in styles.xml

But this might induce a problem with your splashscreen (white screen at startup)... In this case, add the following line to your styles.xml:

 <item name="android:windowDisablePreview">true</item> 

just below the windowIsTranslucent line.

Last chance if the previous tips do not work : target SDK 26 instead o 27.

Quassia answered 31/5, 2018 at 8:2 Comment(2)
Changing the target SDK to 26 instead of 27 worked for me. Changing windowIsTranslucent didn't.Cold
This worked for me using targetSDK: 27. It is specially important since I had a splashscreen configured.Same
F
16

Many people have given a fix, so I'll talk about the source of the problem.

According to the exception log:

Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
    at android.app.Activity.onCreate(Activity.java:1081)
    at android.support.v4.app.SupportActivity.onCreate(SupportActivity.java:66)
    at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:297)
    at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
    at com.nut.blehunter.ui.DialogContainerActivity.onCreate(DialogContainerActivity.java:43)
    at android.app.Activity.performCreate(Activity.java:7372)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
    at android.app.ActivityThread.-wrap12(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
    at android.os.Handler.dispatchMessage(Handler.java:108) 
    at android.os.Looper.loop(Looper.java:166)

The code that triggered the exception in Activity.java

    //Need to pay attention mActivityInfo.isFixedOrientation() and ActivityInfo.isTranslucentOrFloating(ta)
    if (getApplicationInfo().targetSdkVersion >= O_MR1 && mActivityInfo.isFixedOrientation()) {
        final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
        final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
        ta.recycle();

        //Exception occurred
        if (isTranslucentOrFloating) {
            throw new IllegalStateException(
                    "Only fullscreen opaque activities can request orientation");
        }
    }

mActivityInfo.isFixedOrientation():

        /**
        * Returns true if the activity's orientation is fixed.
        * @hide
        */
        public boolean isFixedOrientation() {
            return isFixedOrientationLandscape() || isFixedOrientationPortrait()
                    || screenOrientation == SCREEN_ORIENTATION_LOCKED;
        }
        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        boolean isFixedOrientationPortrait() {
            return isFixedOrientationPortrait(screenOrientation);
        }

        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        public static boolean isFixedOrientationPortrait(@ScreenOrientation int orientation) {
            return orientation == SCREEN_ORIENTATION_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_SENSOR_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_REVERSE_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_USER_PORTRAIT;
        }

        /**
        * Determines whether the {@link Activity} is considered translucent or floating.
        * @hide
        */
        public static boolean isTranslucentOrFloating(TypedArray attributes) {
            final boolean isTranslucent = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsTranslucent, false);
            final boolean isSwipeToDismiss = !attributes.hasValue(com.android.internal.R.styleable.Window_windowIsTranslucent)
                                            && attributes.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false);
            final boolean isFloating = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
            return isFloating || isTranslucent || isSwipeToDismiss;
        }

According to the above code analysis, when TargetSdkVersion>=27, when using SCREEN_ORIENTATION_LANDSCAPE, SCREEN_ORIENTATION_PORTRAIT, and other related attributes, the use of windowIsTranslucent, windowIsFloating, and windowSwipeToDismiss topic attributes will trigger an exception.

After the problem is found, you can change the TargetSdkVersion or remove the related attributes of the theme according to your needs.

Fiorenza answered 12/6, 2018 at 3:58 Comment(2)
Checking the code on master at this moment, it's already removed from framework: mirror/platform_frameworks_base/commit/e83f34cde79c51efb66f31f2770c2e8e572e96db#diff-a9aa0352703240c8ae70f1c83add4bc8 It's interesting to see the commit message.Montford
Can you please show a link to the source code of this part? Is there any workaround that will let me have an Activity with specific orientation AND have a transparent background, so that it will be possible to see what's behind it (including other apps) ?Vandenberg
F
9

I can't agree to most rated answer, because

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

causes an error

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

but this makes it works for me

<style name="TranslucentTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

and use it for your Activity, when you extends from

InterstitialActivity extends AppCompatActivity

in AndroidManifest.xml

    <activity
        android:name=".InterstitialActivity"
        ...
        android:screenOrientation="portrait"
        android:theme="@style/TranslucentTheme" />
Ferebee answered 18/4, 2018 at 11:17 Comment(2)
<item name="android:windowIsTranslucent">false</item> <item name="android:windowFullscreen">true</item> => this fixed it for me on android 8.0. I could still leave screenOrientation in the manifest.Dudleyduds
This doesn't work the same as windowIsTranslucent , because now you can't see what's behind the Activity.Vandenberg
T
9

Just remove this line android:screenOrientation="portrait" of activity in Manifiest.xml

That activity will get orientation from it's previous activity so no need to apply orientation which has <item name="android:windowIsTranslucent">true</item>.

Tecumseh answered 22/11, 2018 at 13:54 Comment(1)
What if the previous activity has a different orientation the what you want in the current activity?Espinoza
S
7

Just Set Orientation of activity in Manifiest.xml

android:screenOrientation="unspecified"

OR for restricted to Portrait Orientation

You can also use in Activity, In onCreate method call before super.onCreate(...) e.g.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        setOrientation(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_xml_layout);
        //...
        //...
}

// Method 
public static void setOrientation(Activity context) {
   if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.O)
        context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
      else
        context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Santasantacruz answered 25/8, 2018 at 18:57 Comment(0)
I
6

it seems when target sdk is pie (api level 28.0) and windowIsTranslucent is true

<item name="android:windowIsTranslucent">true</item>

and you try to access orientation. problem comes with android oreo 8.0 (api level 26) there are two ways to solve this

  1. remove the orientation
  2. or set windowIsTranslucent to false

if you are setting orientation in manifest like this

android:screenOrientation="portrait"

or in activity class like this

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

remove form both places.

and observed when u set windowIsTranslucent to true, it takes orientation from parent activity.

Interbreed answered 2/7, 2019 at 13:36 Comment(0)
P
6

I recently faced the issue and here's the solution.

No need to change the screen orientation parameter which you set at android manifest file.

Just add two folders in

res>values
as  res>values-v26 
and res>values-v27

Then copy your styles.xml and themes.xml file there.

and change the following parameters from TRUE to FALSE.

<item name="android:windowIsTranslucent">true</item>

<item name="android:windowIsTranslucent">false</item>

It will work.

A common bug of Android 8.0

Pauperize answered 16/11, 2019 at 22:32 Comment(0)
U
6

some of the answers wasnt clear for me and didnt work,

so this was causing the error:

<activity
android:name=".ForgotPass_ChangePass"
android:screenOrientation="portrait" <--- // this caused the error
android:windowSoftInputMode="stateHidden|adjustPan|adjustResize"/>

android studio was suggeting to set screenOrientation to fullSensor

android:screenOrientation="fullSensor"

yes this will fix the error but i wan to keep my layout in the portrait mode, and fullSensor will act based on the sensor

"fullSensor" The orientation is determined by the device orientation sensor for any of the 4 orientations. This is similar to "sensor" except this allows any of the 4 possible screen orientations, regardless of what the device will normally do (for example, some devices won't normally use reverse portrait or reverse landscape, but this enables those). Added in API level 9.

source: android:screenOrientation

so the solution that worked for me i used "nosensor" :

 <activity
        android:name=".ForgotPass_ChangePass"
        android:screenOrientation="nosensor"
        android:windowSoftInputMode="stateHidden|adjustPan|adjustResize"/>

"nosensor" The orientation is determined without reference to a physical orientation sensor. The sensor is ignored, so the display will not rotate based on how the user moves the device.

see android documentation here

Usance answered 30/6, 2021 at 15:9 Comment(0)
P
5

in the manifest file set second activity parentActivityName as first activity and remove the screenOrientation parameter to the second activity. it means your first activity is the parent and decide to an orientation of your second activity.

<activity
        android:name=".view.FirstActiviy"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme" />

<activity
        android:name=".view.SecondActivity"
        android:parentActivityName=".view.FirstActiviy"
        android:theme="@style/AppTheme.Transparent" />
Prissy answered 21/7, 2018 at 14:26 Comment(0)
T
4

I had the same problem, and my solution was to eliminate the line

android:screenOrientation="portrait"

and then add this in the activity:

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Tricolor answered 16/8, 2018 at 18:19 Comment(1)
Please use English on Stack Overflow. Thanks!Revkah
A
4

It is a conflict (bug) between Themes inside style.xml file in android versions 7 (Api levels 24,25) & 8 (api levels 26,27), when you have

android:screenOrientation="portrait" :inside specific activity (that crashes) in AndroidManifest.xml

&

<item name="android:windowIsTranslucent">true</item> 

in the theme that applied to that activity inside style.xml

It can be solve by these ways according to your need :

1- Remove on of the above mentioned properties that make conflict

2- Change Activity orientation to one of these values as you need : unspecified or behind and so on that can be found here : Google reference for android:screenOrientation `

3- Set the orientation programmatically in run time

Alina answered 7/1, 2019 at 15:18 Comment(8)
Tried this solution, but app still crashes: I need portrait transparent activity so I need both this options. Tried set in manifest screenOrientation unspecified, but no luck.Shortstop
No. I tried remove orientation in manifest at all, and make activity fullscreen, but it still crashes. Only on 1 device - honor 9 lite. On Samsung it works ok.Shortstop
Setting the orientation programmatically also causes the crash. How did you use it exactly?Vandenberg
@androiddeveloper how can I access your source code?! I must see what you didAlina
@HamedJaliliani Setting it programmaticaly is as such, for example: ` setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);`Vandenberg
@androiddeveloper what is your activity tag code in manifest, version of android that you face this error & logcat error?Alina
@HamedJaliliani Here's a sample code: issuetracker.google.com/issues/131534974 . Would be easier than to explain in a restricted comment section.Vandenberg
It's 2023 and we just ran into this! We have targetSdkVersion 32 and minSdkVersion 26 This solution is closest to what worked for us, we just removed in the manifest android:screenOrientation="portrait" for all activities that were also having android:windowIsTranslucent doneCoriander
S
3

After doing some research, it seems that this problem may be due to a google bug. For me, I was able to leave this line in my Activities onCreate method:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

AND I changed my targetSdkVersion to 26. Having that line in my onCreate still resulted in a crash while my targetSdkVersion was still set at 27. Since no one else's solution has worked for me thus far, I found that this works as a temporary fix for now.

Swivel answered 26/9, 2018 at 1:4 Comment(3)
This one worked for me by setting targetSdkVersion to 26, android:screenOrientation="portrait" and <item name="android:windowIsTranslucent">true</item>Bara
@Bara for me tooPrepossess
But eventually you will have to set the targetSdkVersion to 28 this year : support.google.com/googleplay/android-developer/answer/… . What will you do?Vandenberg
V
3

only 8.0.0 throw the exception, above 8.0 has remove the exception

8.0.0 throw the exception

Venturous answered 4/1, 2019 at 13:10 Comment(3)
Android 7, 7.1 , 8.0 , 8.1 all have this problemAlina
appInfo.targetSdkVersion > O throw the exceptionVenturous
Its checking the target sdk version. It doesn't matter what sdk version the device is actually running, you're compiling against Android O (28) but not following the conventions of that version of the platform.Thermy
G
3

Use

android:screenOrientation="behind"

And Theme

<style name="translucent" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">#beaaaaaa</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowAnimationStyle">@android:style/Animation</item>
    <item name="android:typeface">normal</item>
    <item name="android:windowSoftInputMode">adjustPan</item>
    <item name="windowActionBar">false</item>
</style>
Gallice answered 2/7, 2019 at 8:15 Comment(0)
H
2

Probably you showing Activity looking like Dialog(non-fullscreen), so remove screenOrientation from Manifest or from code. This will fix the issue.

Hawkweed answered 17/4, 2018 at 12:0 Comment(1)
Hmm very strange, for me that was the case. Try running the app on different Android versions, see what will be the result this may help you...Hawkweed
S
2

I faced this problem only in SDK 26 (8.0.0) if using windowIsTranslucent 'true' and forcefully setting orientation:

Here's the solution:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);   

        // fixing portrait mode problem for SDK 26 if using windowIsTranslucent = true
        if (Build.VERSION.SDK_INT == 26) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }        
    }



       <style name="SplashActivty" parent="AppTheme">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
    </style>



<!-- Splash screen -->
        <activity
            android:name="edu.aku.family_hifazat.activities.SplashActivity"
            android:label="@string/app_name"
            android:screenOrientation="unspecified"
            android:theme="@style/SplashActivty">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>
Screamer answered 28/9, 2018 at 7:13 Comment(1)
But then you lose the functionality of actually having the orientation set to what you wanted.Vandenberg
I
2

I was getting this error when I try to capture image or take image from gallery what works for me is to remove both

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

and

android:screenOrientation="portrait"

now my activity is using this theme:

  <style name="Transparent" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:colorBackgroundCacheHint">@null</item>
        <item name="android:windowAnimationStyle">@android:style/Animation</item>
        <item name="android:windowIsTranslucent">false</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>
Ichnite answered 2/1, 2019 at 5:6 Comment(1)
This doesn't work, as windowIsFloating causes the same crash as windowIsTranslucent .Vandenberg
K
2

The only thing that worked for me was changing

android:screenOrientation="portrait"

to

android:screenOrientation="unspecified"

in the manifest for all translucent activities.

That way it is compatible with all API versions since the translucent activity seems to inherit its orientation from the parent activity as of targetApi: 28.

The style can be left as it is including <item name="android:windowIsTranslucent">true</item>.

Kwon answered 1/4, 2019 at 13:59 Comment(4)
Tried this solution, but app still crashesShortstop
But then you lose the function of setting the orientationVandenberg
@androiddeveloper: The way I understand it the orientation will be inherited from the parent activity. If you want to explicitly set another orientation on the translucent activity that wouldn't work this way...Kwon
Sometimes you can't have control of the previous Activity. Sometimes you want to show your transparent one on top of what the user currently sees. So this can't help :(Vandenberg
P
2

I resolved this issue by removing android:screenOrientation="portrait" and added below code into my onCreate

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

while my theme properties are

<item name="android:windowIsTranslucent">true</item>
<item name="android:windowDisablePreview">true</item>
Protolanguage answered 24/2, 2020 at 3:29 Comment(0)
V
1

I do not know if this is a bug from Google or an intended behavior but I (at least momentarily) solved it by changing compileSdkVersion and targetSdkVersion back to 26 in Gradle...

Vivianne answered 19/3, 2018 at 23:10 Comment(4)
You shouldn't lower the targetsdk level. Your app will be blocked from the play store eventually. Always target the latest Android Api level android-developers.googleblog.com/2017/12/…Supination
@Supination : wrong. You can target 26 and be available on 28 on the store.Quassia
Correct, I wrote 'eventually' if you build your app targeting an older api level you will be in a world of pain when you are forced to updateSupination
This is not a solution but a workaround. One day you have to migrate your app to 28 and hence!Impower
L
1

If you haven't resolved your problem just register the ad activity in the manifest like this:

<activity
android:name="com.google.android.gms.ads.AdActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
tools:replace="android:theme"
 />

You also need to update to the latest version of the sdk.

Leibniz answered 5/4, 2018 at 10:28 Comment(0)
R
1

this happened after 27,use targetSdkVersion 26 replace, wait for google fixed it

Ruth answered 18/7, 2018 at 4:4 Comment(3)
Please provide any reference (link or quoted) when posting an answer. So future users can understand easily. Also, welcome to the SO Community.Kilter
@MohammedsalimShivani Here: issuetracker.google.com/issues/68454482#comment4 "Our engineering team has fixed this issue. It will be available in a future Android release, so please keep an eye on the release notes."Vandenberg
This is bad adviceMelesa
D
0

If the activity created by yourself, you can try this in the Activity:

@Override
public void setRequestedOrientation(int requestedOrientation) {
    try {
        super.setRequestedOrientation(requestedOrientation);
    } catch (IllegalStateException e) {
        // Only fullscreen activities can request orientation
        e.printStackTrace();
    }
}

This should be the easiest solution.

Diode answered 10/1, 2019 at 7:21 Comment(0)
B
0

I've just removed the tags "portrait" from the non full-screen elements and everything went fine.

android:screenOrientation="portrait"
Burgage answered 23/5, 2019 at 15:57 Comment(0)
F
0

Please check the style of your Activity and make sure if you are not using any Translucent related things, change the style to alternate. So that we can fix this problem.

android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
Farly answered 10/1, 2020 at 7:52 Comment(0)
S
0

In Oreo API 27 transparent and translucent activity can’t request of orientation. Because the previous non opaque activity might have a different orientation as compared to top transparent activity which might create uneven UI behaviour.

opaque activity A (portrait) → transparent activity B (landscape) If above case was possible we might able to see A portrait from B’s transparent landscape orientation. Which will cut off A’s top and bottom.

A better solution would be to set A’s orientation to portrait if we want B to be portrait. It will inherit the last opaque activity orientation. Or just make the activity opaque and add your own orientation.

Settera answered 31/8, 2023 at 8:8 Comment(0)
V
0

An alternative to just avoid the theme itself is to try to set the orientation if possible, all in code:

/**tries to set the orientation if possible. Returns true iff succeeded. Not an issue after Android O, because of this: https://mcmap.net/q/109309/-java-lang-illegalstateexception-only-fullscreen-opaque-activities-can-request-orientation/878126*/
fun requestedOrientationCompat(activity: Activity, requestedOrientation: Int): Boolean {
    if (VERSION.SDK_INT != VERSION_CODES.O) {
        activity.requestedOrientation = requestedOrientation
        return true
    }
    // based on https://mcmap.net/q/109309/-java-lang-illegalstateexception-only-fullscreen-opaque-activities-can-request-orientation https://android.googlesource.com/platform/frameworks/base/+/d4ecffae67fa0dea03c581ca26f76b87a14be763%5E%21/
    // public static boolean isTranslucentOrFloating(TypedArray attributes) {
    // ...   return isFloating || isTranslucent || isSwipeToDismiss;
    val window = activity.window
    val attributes = window.windowStyle
    //  https://developer.android.com/reference/android/R.styleable#Window_windowIsTranslucent
    // final boolean isTranslucent = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsTranslucent, false);
    val styleableWindowIsTranslucent = 5
    val isTranslucent = attributes.getBoolean(styleableWindowIsTranslucent, false)
    // final boolean isSwipeToDismiss = !attributes.hasValue(com.android.internal.R.styleable.Window_windowIsTranslucent)
    //      && attributes.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false);
    @Suppress("DEPRECATION")
    val isSwipeToDismiss =
            !attributes.hasValue(styleableWindowIsTranslucent) && window.hasFeature(Window.FEATURE_SWIPE_TO_DISMISS)
    // https://developer.android.com/reference/android/R.styleable#Window_windowIsFloating
    // final boolean isFloating = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
    val styleableWindowIsFloating = 4
    val isFloating = attributes.getBoolean(styleableWindowIsFloating, false);
    val isTranslucentOrFloating=isFloating || isTranslucent || isSwipeToDismiss
    if(isTranslucentOrFloating)
        return false
    activity.requestedOrientation = requestedOrientation
    return true
}

Alternative for those who prefer extension function:

/**tries to set the orientation if possible. Returns true iff succeeded. Not an issue after Android O, because of this: https://mcmap.net/q/109309/-java-lang-illegalstateexception-only-fullscreen-opaque-activities-can-request-orientation/878126*/
fun Activity.requestedOrientationCompat(requestedOrientation: Int): Boolean{
    if (VERSION.SDK_INT != VERSION_CODES.O) {
        this.requestedOrientation = requestedOrientation
        return true
    }
    // based on https://mcmap.net/q/109309/-java-lang-illegalstateexception-only-fullscreen-opaque-activities-can-request-orientation https://android.googlesource.com/platform/frameworks/base/+/d4ecffae67fa0dea03c581ca26f76b87a14be763%5E%21/
    // public static boolean isTranslucentOrFloating(TypedArray attributes) {
    // ...   return isFloating || isTranslucent || isSwipeToDismiss;
    val attributes = window.windowStyle
    //  https://developer.android.com/reference/android/R.styleable#Window_windowIsTranslucent
    // final boolean isTranslucent = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsTranslucent, false);
    val styleableWindowIsTranslucent = 5
    val isTranslucent = attributes.getBoolean(styleableWindowIsTranslucent, false)
    // final boolean isSwipeToDismiss = !attributes.hasValue(com.android.internal.R.styleable.Window_windowIsTranslucent)
    //      && attributes.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false);
    @Suppress("DEPRECATION")
    val isSwipeToDismiss =
            !attributes.hasValue(styleableWindowIsTranslucent) && window.hasFeature(Window.FEATURE_SWIPE_TO_DISMISS)
    // https://developer.android.com/reference/android/R.styleable#Window_windowIsFloating
    // final boolean isFloating = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
    val styleableWindowIsFloating = 4
    val isFloating = attributes.getBoolean(styleableWindowIsFloating, false);
    val isTranslucentOrFloating=isFloating || isTranslucent || isSwipeToDismiss
    if(isTranslucentOrFloating)
        return false
    this.requestedOrientation = requestedOrientation
    return true
}
Vandenberg answered 2/1 at 8:45 Comment(0)
A
-1

I had the same problem and I fixed it just by setting this: <item name="android:windowIsFloating">false</item> in styles.xml

Agueweed answered 5/6, 2019 at 13:39 Comment(0)
R
-2

Try remove lines of your theme:

<item name="android:windowIsTranslucent">true</item>

and

<item name="android:windowIsFloating">true</item>

after this, add android:screenOrientation="portrait" in your activity.

Retiform answered 22/2, 2019 at 1:27 Comment(0)
A
-3

User extend AppCompatActivity & it will work !!

Allegedly answered 8/10, 2018 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.