AVEbrahimi
AVEbrahimi

Reputation: 19164

Detecting if Android foldable device is open and flat or closed is not working always

I tried detecting when foldable device is opened (FLAT) and update ui, this is the code, but the problem is sometimes it works and sometimes it does not, I mean sometime I open the device, callbak is called, but displayFeatures is empty:

private void checkIfDeviceIsFold() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            windowInfoTracker =
                    new WindowInfoTrackerCallbackAdapter(WindowInfoTracker.getOrCreate(this));
            deviceIsFoldable = getApplication().getPackageManager().
                    hasSystemFeature(PackageManager.FEATURE_SENSOR_HINGE_ANGLE);
            // Log deviceIsFoldable
            Log.d(Constants.TAG, "Device is foldable: " + deviceIsFoldable);
        } else
            deviceIsFoldable = false;
    }

@Override
protected void onStart() {
    super.onStart();
    windowInfoTracker.addWindowLayoutInfoListener(
            this, runOnUiThreadExecutor(), layoutStateChangeCallback);
    Log.d(Constants.TAG,"Study:onStart");
}

private final LayoutStateChangeCallback layoutStateChangeCallback =
        new LayoutStateChangeCallback();

class LayoutStateChangeCallback implements Consumer<WindowLayoutInfo> {

    @Override
    public void accept(WindowLayoutInfo newLayoutInfo) {
        FoldableHelper.FoldableLayoutInfo resultInfo = FoldableHelper.updateLayout(newLayoutInfo, StudyDisplay.this);
        Log.d(Constants.TAG, "FoldableHelper : newLayoutInfo : " + resultInfo.state);
        Log.d(Constants.TAG, "Study Fold state : newLayoutInfo : " + newLayoutInfo.toString());
        deviceIsFoldableAndItsOpen = false;
        updateLayoutForScreenSize();
        // Use newLayoutInfo to update the Layout
        List<DisplayFeature> displayFeatures = newLayoutInfo.getDisplayFeatures();
        for (DisplayFeature feature : displayFeatures) {
            Log.d(Constants.TAG, "Study Fold feature : " + feature);
            if (feature instanceof FoldingFeature) {
                // Use information from the feature object
                FoldingFeature foldingFeature = (FoldingFeature) feature;
                FoldingFeature.State state = foldingFeature.getState();
                // Use hingeAngle to update the layout
                Log.d(Constants.TAG, "Study Fold state : " + state);
                // true even if half openned
                deviceIsFoldableAndItsOpen = true;
                updateLayoutForScreenSize();
            }
        }
    }
}

Upvotes: 0

Views: 104

Answers (0)

Related Questions