public abstract class

LoadingViewer

extends Viewer

 java.lang.Object

androidx.fragment.app.Fragment

androidx.pdf.viewer.Viewer

↳androidx.pdf.viewer.LoadingViewer

Subclasses:

PdfViewer

Gradle dependencies

compile group: 'androidx.pdf', name: 'pdf-viewer', version: '1.0.0-alpha02'

  • groupId: androidx.pdf
  • artifactId: pdf-viewer
  • version: 1.0.0-alpha02

Artifact androidx.pdf:pdf-viewer:1.0.0-alpha02 it located at Google repository (https://maven.google.com/)

Overview

This base class offers logic to save the DisplayData it receives (without any heavy contents) and restore it after a destroy/create cycle, including re-fetching (on a separate thread) the actual contents from the saved data. In all cases, the actual contents are delivered to the sub-class via LoadingViewer.onContentsAvailable(DisplayData, Bundle) after its view hierarchy has been built (after LoadingViewer.onCreateView(LayoutInflater, ViewGroup, Bundle)).

This class introduces one extra life-cycle callback:

In order to work as expected, it requires the parent frame of the viewer to be created at the time it's being restored (which means during Activity#onCreate).

Summary

Fields
protected FetchermFetcher

protected static final booleanSELF_MANAGED_CONTENTS

Constant used by subclasses to turn LoadingViewer.mSelfManagedContents on.

from ViewerKEY_DATA, mContainer, mIsPasswordProtected, mViewState
from FragmentmPreviousWho
Constructors
protectedLoadingViewer()

protectedLoadingViewer(boolean selfManagedContents)

Constructor allowing a subclass to prevent the default behaviour of re-fetching the contents when just the view needs to be re-created.

Methods
public Viewerfeed(DisplayData contents)

Feed this Viewer with contents to be displayed.

protected abstract voidonContentsAvailable(DisplayData contents, Bundle savedState)

Callback called when the full contents is re-loaded.

public ViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view.

public voidonDestroyView()

Called when the view previously created by Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) has been detached from the fragment.

public voidonStart()

Called when the Fragment is visible to the user.

public voidonStop()

Called when the Fragment is no longer started.

protected voidpostContentsAvailable(DisplayData contents, Bundle savedState)

Posts a LoadingViewer.onContentsAvailable(DisplayData, Bundle) method to be run as soon as permitted (when this Viewer has its view hierarchy built up and LoadingViewer.onCreateView(LayoutInflater, ViewGroup, Bundle) has finished).

protected voidrestoreContents(Bundle savedState)

Restores the contents of this Viewer when it is automatically restored by android.

public LoadingViewersetFetcher(Fetcher fetcher)

Sets the fetcher to be used by the viewer and returns the viewer.

from ViewerconfigureShareScroll, destroyView, finalize, isShowing, isStarted, onActivityCreated, onCreate, onDestroy, onEnter, onExit, participateInAccessibility, postEnter, saveToArguments, viewState
from Fragmentdump, equals, getActivity, getAllowEnterTransitionOverlap, getAllowReturnTransitionOverlap, getArguments, getChildFragmentManager, getContext, getDefaultViewModelCreationExtras, getDefaultViewModelProviderFactory, getEnterTransition, getExitTransition, getFragmentManager, getHost, getId, getLayoutInflater, getLayoutInflater, getLifecycle, getLoaderManager, getParentFragment, getParentFragmentManager, getReenterTransition, getResources, getRetainInstance, getReturnTransition, getSavedStateRegistry, getSharedElementEnterTransition, getSharedElementReturnTransition, getString, getString, getTag, getTargetFragment, getTargetRequestCode, getText, getUserVisibleHint, getView, getViewLifecycleOwner, getViewLifecycleOwnerLiveData, getViewModelStore, hashCode, hasOptionsMenu, instantiate, instantiate, isAdded, isDetached, isHidden, isInLayout, isMenuVisible, isRemoving, isResumed, isStateSaved, isVisible, onActivityResult, onAttach, onAttach, onAttachFragment, onConfigurationChanged, onContextItemSelected, onCreateAnimation, onCreateAnimator, onCreateContextMenu, onCreateOptionsMenu, onDestroyOptionsMenu, onDetach, onGetLayoutInflater, onHiddenChanged, onInflate, onInflate, onLowMemory, onMultiWindowModeChanged, onOptionsItemSelected, onOptionsMenuClosed, onPause, onPictureInPictureModeChanged, onPrepareOptionsMenu, onPrimaryNavigationFragmentChanged, onRequestPermissionsResult, onResume, onSaveInstanceState, onViewCreated, onViewStateRestored, postponeEnterTransition, postponeEnterTransition, registerForActivityResult, registerForActivityResult, registerForContextMenu, requestPermissions, requireActivity, requireArguments, requireContext, requireFragmentManager, requireHost, requireParentFragment, requireView, setAllowEnterTransitionOverlap, setAllowReturnTransitionOverlap, setArguments, setEnterSharedElementCallback, setEnterTransition, setExitSharedElementCallback, setExitTransition, setHasOptionsMenu, setInitialSavedState, setMenuVisibility, setReenterTransition, setRetainInstance, setReturnTransition, setSharedElementEnterTransition, setSharedElementReturnTransition, setTargetFragment, setUserVisibleHint, shouldShowRequestPermissionRationale, startActivity, startActivity, startActivityForResult, startActivityForResult, startIntentSenderForResult, startPostponedEnterTransition, toString, unregisterForContextMenu
from java.lang.Objectclone, getClass, notify, notifyAll, wait, wait, wait

Fields

protected static final boolean SELF_MANAGED_CONTENTS

Constant used by subclasses to turn LoadingViewer.mSelfManagedContents on.

protected Fetcher mFetcher

Constructors

protected LoadingViewer()

protected LoadingViewer(boolean selfManagedContents)

Constructor allowing a subclass to prevent the default behaviour of re-fetching the contents when just the view needs to be re-created. Useful for viewers that keep references to the contents when their view hierarchy is destroyed .

Parameters:

selfManagedContents: Use LoadingViewer.SELF_MANAGED_CONTENTS for the described setting.

Methods

public Viewer feed(DisplayData contents)

Feed this Viewer with contents to be displayed.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between Fragment.onCreate(Bundle) and Fragment.onViewCreated(View, Bundle).

A default View can be returned by calling Fragment.Fragment(int) in your constructor. Otherwise, this method returns null.

It is recommended to only inflate the layout in this method and move logic that operates on the returned View to Fragment.onViewCreated(View, Bundle).

If you return a View from here, you will later be called in Fragment.onDestroyView() when the view is being released.

Parameters:

inflater: The LayoutInflater object that can be used to inflate any views in the fragment,
container: If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.
savedInstanceState: If non-null, this fragment is being re-constructed from a previous saved state as given here.

Returns:

Return the View for the fragment's UI, or null.

public void onStart()

Called when the Fragment is visible to the user. This is generally tied to of the containing Activity's lifecycle.

public void onStop()

Called when the Fragment is no longer started. This is generally tied to of the containing Activity's lifecycle.

public void onDestroyView()

Called when the view previously created by Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) has been detached from the fragment. The next time the fragment needs to be displayed, a new view will be created. This is called after Fragment.onStop() and before Fragment.onDestroy(). It is called regardless of whether Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) returned a non-null view. Internally it is called after the view's state has been saved but before it has been removed from its parent.

protected abstract void onContentsAvailable(DisplayData contents, Bundle savedState)

Callback called when the full contents is re-loaded. This method should always run after LoadingViewer.onCreateView(LayoutInflater, ViewGroup, Bundle) and only on the UI thread.

Parameters:

contents: The fully-loaded contents.
savedState: If this instance is reborn, the saved state that was given to onCreate.

protected void postContentsAvailable(DisplayData contents, Bundle savedState)

Posts a LoadingViewer.onContentsAvailable(DisplayData, Bundle) method to be run as soon as permitted (when this Viewer has its view hierarchy built up and LoadingViewer.onCreateView(LayoutInflater, ViewGroup, Bundle) has finished). It might run right now if the Viewer is currently started.

public LoadingViewer setFetcher(Fetcher fetcher)

Sets the fetcher to be used by the viewer and returns the viewer.

protected void restoreContents(Bundle savedState)

Restores the contents of this Viewer when it is automatically restored by android.

Source

/*
 * Copyright 2024 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.pdf.viewer;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.pdf.data.DisplayData;
import androidx.pdf.fetcher.Fetcher;
import androidx.pdf.util.Preconditions;

import com.google.errorprone.annotations.CanIgnoreReturnValue;

/**
 * This base class offers logic to save the {@link DisplayData} it receives (without any heavy
 * contents) and restore it after a destroy/create cycle, including re-fetching (on a separate
 * thread) the actual contents from the saved data. In all cases, the actual contents are
 * delivered to the sub-class via {@link #onContentsAvailable} after its view hierarchy has been
 * built (after {@link #onCreateView}).
 * <p>
 * This class introduces one extra life-cycle callback:
 * <ul>
 * <li>{@link #onContentsAvailable}, as explained above, will run after {@link #onCreateView} and
 *     deliver the full file contents.
 * </ul>
 * In order to work as expected, it requires the parent frame of the viewer to be created at the
 * time it's being restored (which means during Activity#onCreate).
 * <p>
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public abstract class LoadingViewer extends Viewer {

    /** Constant used by subclasses to turn {@link #mSelfManagedContents} on. */
    protected static final boolean SELF_MANAGED_CONTENTS = true;

    /**
     * True if the subclass keeps references to the contents when the view hierarchy is
     * destroyed.
     */
    private final boolean mSelfManagedContents;

    /** A saved {@link #onContentsAvailable} runnable to be run after {@link #onCreateView}. */
    private Runnable mDelayedContentsAvailable;

    private boolean mHasContents;

    @NonNull
    protected Fetcher mFetcher;

    protected LoadingViewer() {
        this(false);
    }

    /**
     * Constructor allowing a subclass to prevent the default behaviour of re-fetching the contents
     * when just the view needs to be re-created. Useful for viewers that keep references to the
     * contents when their view hierarchy is destroyed .
     *
     * @param selfManagedContents Use {@link #SELF_MANAGED_CONTENTS} for the described setting.
     */
    protected LoadingViewer(boolean selfManagedContents) {
        this.mSelfManagedContents = selfManagedContents;
    }

    /** Feed this Viewer with contents to be displayed. */
    @NonNull
    @CanIgnoreReturnValue
    public Viewer feed(@NonNull DisplayData contents) {
        saveToArguments(contents);
        postContentsAvailable(contents, null);
        return this;
    }

    @NonNull
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedState) {
        View result = super.onCreateView(inflater, container, savedState);
        if (mFetcher == null) {
            // When changing device languages the system creates a new ImageViewer and the old
            // instance with a null fetcher stays around, even though it has been detached from the
            // view hierarchy, which is when this case happens. Logging it is sufficient as the
            // second instance will have the fetcher injected as expected.
            mViewState.set(ViewState.ERROR);
            return result;
        }

        if (!mHasContents && mDelayedContentsAvailable == null) {
            restoreContents(savedState);
        }
        return result;
    }

    @Override
    public void onStart() {
        if (mDelayedContentsAvailable != null) {
            mDelayedContentsAvailable.run();
        }
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (!mSelfManagedContents) {
            mHasContents = false;
        }
    }

    /**
     * Callback called when the full contents is re-loaded. This method should always run after
     * {@link #onCreateView} and only on the UI thread.
     *
     * @param contents   The fully-loaded contents.
     * @param savedState If this instance is reborn, the saved state that was given to onCreate.
     */
    @MainThread
    protected abstract void onContentsAvailable(
            @NonNull DisplayData contents, @Nullable Bundle savedState);

    /**
     * Posts a {@link #onContentsAvailable} method to be run as soon as permitted (when this Viewer
     * has its view hierarchy built up and {@link #onCreateView} has finished). It might run right
     * now if the Viewer is currently started.
     */
    protected void postContentsAvailable(final @NonNull DisplayData contents,
            @Nullable final Bundle savedState) {
        Preconditions.checkState(mDelayedContentsAvailable == null, "Already waits for contents");

        if (isStarted()) {
            onContentsAvailable(contents, savedState);
            mHasContents = true;
        } else {
            mDelayedContentsAvailable =
                    () -> {
                        Preconditions.checkState(
                                !mHasContents, "Received contents while restoring another copy");
                        onContentsAvailable(contents, savedState);
                        mDelayedContentsAvailable = null;
                        mHasContents = true;
                    };
        }
    }

    /** Sets the fetcher to be used by the viewer and returns the viewer. */
    @NonNull
    public LoadingViewer setFetcher(@NonNull Fetcher fetcher) {
        this.mFetcher = Preconditions.checkNotNull(fetcher);
        return this;
    }

    /**
     * Restores the contents of this Viewer when it is automatically restored by android.
     */
    protected void restoreContents(@Nullable Bundle savedState) {
        Preconditions.checkState(mFetcher != null, "must run after ViewerManager#inject");
        Bundle dataBundle = getArguments().getBundle(KEY_DATA);
        if (dataBundle != null) {
            try {
                DisplayData restoredData = DisplayData.fromBundle(dataBundle);
                postContentsAvailable(restoredData, savedState);
            } catch (Exception e) {
                // This can happen if the data is an instance of StreamOpenable, and the client
                // app that owns it has been killed by the system. We will still recover,
                // but log this.
                mViewState.set(ViewState.ERROR);
            }
        }
    }
}