AmbientModeSupport

public final class AmbientModeSupport extends Fragment implements LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, LifecycleOwner, SavedStateRegistryOwner, ActivityResultCaller

Object
   ↳ Fragment
     ↳ AmbientModeSupport

Use this as a headless Fragment to add ambient support to an Activity on Wearable devices.

The application that uses this should add the WAKE_LOCK permission to its manifest.

The following describes the general use of this class:

Create a subclass of one of the FragmentActivity classes and implement the AmbientCallbackProvider interface. Override the getAmbientCallback method to provide the callbacks required for reacting to the ambient events from the Android system. If a valid AmbientCallback is not provided (either no implementation of the AmbientCallbackProvider interface, or returning null from getAmbientCallback), then ambient mode will NOT be enabled.

The primary entry point for this code is the attach method. It should be called with an FragmentActivity as an argument and that FragmentActivity will then be able to receive ambient lifecycle events through an AmbientCallback. The FragmentActivity will also receive a AmbientController object from the attachment which can be used to query the current status of the ambient mode.

An example of how to implement the AmbientCallbackProvider interface, attach AmbientModeSupport to your FragmentActivity and use the AmbientController can be found below:

public class MyActivity extends FragmentActivity
    implements AmbientModeSupport.AmbientCallbackProvider {
    {@literal @}Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState)
        ...
        AmbientModeSupport.AmbientController controller = AmbientModeSupport.attach(this);
        boolean isAmbient = controller.isAmbient();
    }
    {@literal @}Override
    AmbientModeSupport.AmbientCallback getAmbientCallback() {
        return new AmbientModeSupport.AmbientCallback() {
            public void onEnterAmbient(Bundle ambientDetails) {...}
            public void onExitAmbient(Bundle ambientDetails) {...}
        }
    }
}

Summary

Nested types

AmbientModeSupport.AmbientCallback

Callback to receive ambient mode state changes.

AmbientModeSupport.AmbientCallbackProvider

Interface for any Activity that wishes to implement Ambient Mode.

AmbientModeSupport.AmbientController

A class for interacting with the ambient mode on a wearable device.

Constants

static final @NonNull String

Property in bundle passed to {@code AmbientCallback#onEnterAmbient(Bundle)} to indicate whether burn-in protection is required.

static final @NonNull String

Property in bundle passed to {@code AmbientCallback#onEnterAmbient(Bundle)} to indicate whether the device has low-bit ambient mode.

static final @NonNull String

Fragment tag used by default when adding AmbientModeSupport to add ambient support to a FragmentActivity.

Public constructors

Constructor

Public methods

static @NonNull AmbientModeSupport.AmbientController
<T extends FragmentActivity> attach(@NonNull T activity)

Attach ambient support to the given activity.

@Override @NonNull void
dump(
    @NonNull String prefix,
    @NonNull FileDescriptor fd,
    @NonNull PrintWriter writer,
    @NonNull Array<@NonNull String> args
)

Print the Fragments's state into the given stream.

@Override @CallSuper @NonNull void

Called when a fragment is first attached to its context.

@Override @CallSuper @NonNull void
onCreate(@NonNull Bundle savedInstanceState)

Called to do initial creation of a fragment.

@Override @CallSuper @NonNull void

Called when the fragment is no longer in use.

@Override @CallSuper @NonNull void

Called when the fragment is no longer attached to its activity.

@Override @CallSuper @NonNull void

Called when the Fragment is no longer resumed.

@Override @CallSuper @NonNull void

Called when the fragment is visible to the user and actively running.

@Override @CallSuper @NonNull void

Called when the Fragment is no longer started.

Inherited methods

From class ActivityResultCaller
abstract @NonNull ActivityResultLauncher<@NonNull I>

Register a request to start an activity for result, designated by the given contract.

abstract @NonNull ActivityResultLauncher<@NonNull I>

Register a request to start an activity for result, designated by the given contract.

From class ComponentCallbacks
From class Fragment
final @Override @NonNull boolean

Subclasses can not override equals().

final @Nullable FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

@NonNull boolean

Returns whether the the exit transition and enter transition overlap or not.

@NonNull boolean

Returns whether the the return transition and reenter transition overlap or not.

final @Nullable Bundle

Return the arguments supplied when the fragment was instantiated, if any.

final @NonNull FragmentManager

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

@Nullable Context

Return the Context this fragment is currently associated with.

@NonNull @Override ViewModelProvider.Factory

Returns the default that should be used when no custom Factory} is provided to the constructors.

@Nullable Object

Returns the Transition that will be used to move Views into the initial scene.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

final @Nullable FragmentManager

This method is deprecated.

This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

final @Nullable Object

Return the host object of this fragment.

final @NonNull int

Return the identifier this fragment is known by.

final @NonNull LayoutInflater

Returns the cached LayoutInflater used to inflate Views of this Fragment.

@Override @NonNull Lifecycle

Returns the Lifecycle of the provider.

@NonNull LoaderManager

This method is deprecated.

Use LoaderManager.getInstance(this).

final @Nullable Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull FragmentManager

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

@Nullable Object

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

final @NonNull Resources

Return requireActivity().getResources().

final @NonNull boolean

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

final @NonNull @Override SavedStateRegistry

Returns owned SavedStateRegistry

@Nullable Object

Returns the Transition that will be used for shared elements transferred into the content Scene.

@Nullable Object

Return the Transition that will be used for shared elements transferred back during a pop of the back stack.

final @NonNull String

Return a localized string from the application's package's default string table.

final @NonNull String
getString(
    @StringRes @NonNull int resId,
    @Nullable Array<@NonNull Object> formatArgs
)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

final @Nullable String

Get the tag name of the fragment, if specified.

final @Nullable Fragment

This method is deprecated.

Instead of using a target fragment to pass results, use setFragmentResult to deliver results to FragmentResultListener instances registered by other fragments via setFragmentResultListener.

final @NonNull int

This method is deprecated.

When using the target fragment replacement of setFragmentResultListener and setFragmentResult, consider using setArguments to pass a {@code requestKey} if you need to support dynamic request keys.

final @NonNull CharSequence
getText(@StringRes @NonNull int resId)

Return a localized, styled CharSequence from the application's package's default string table.

@NonNull boolean

This method is deprecated.

Use setMaxLifecycle instead.

@Nullable View

Get the root view for the fragment's layout (the one returned by onCreateView), if provided.

@MainThread @NonNull LifecycleOwner

Get a LifecycleOwner that represents the Fragment's View lifecycle.

@NonNull LiveData<@NonNull LifecycleOwner>

Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.

@NonNull @Override ViewModelStore

Returns the ViewModelStore associated with this Fragment

final @Override @NonNull int

Subclasses can not override hashCode().

static @NonNull Fragment

This method is deprecated.

Use getFragmentFactory and instantiate

static @NonNull Fragment
instantiate(
    @NonNull Context context,
    @NonNull String fname,
    @Nullable Bundle args
)

This method is deprecated.

Use getFragmentFactory and instantiate, manually calling setArguments on the returned Fragment.

final @NonNull boolean

Return true if the fragment is currently added to its activity.

final @NonNull boolean

Return true if the fragment has been explicitly detached from the UI.

final @NonNull boolean

Return true if the fragment has been hidden.

final @NonNull boolean

Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag.

final @NonNull boolean

Return true if this fragment is currently being removed from its activity.

final @NonNull boolean

Return true if the fragment is in the resumed state.

final @NonNull boolean

Returns true if this fragment is added and its state has already been saved by its host.

final @NonNull boolean

Return true if the fragment is currently visible to the user.

@MainThread @CallSuper @NonNull void
onActivityCreated(@Nullable Bundle savedInstanceState)

This method is deprecated.

use onViewCreated for code touching the Fragment's view and onCreate for other initialization.

@NonNull void
onActivityResult(
    @NonNull int requestCode,
    @NonNull int resultCode,
    @Nullable Intent data
)

This method is deprecated.

use registerForActivityResult with the appropriate ActivityResultContract and handling the result in the callback.

@MainThread @CallSuper @NonNull void

This method is deprecated.

See onAttach.

@MainThread @NonNull void

This method is deprecated.

The responsibility for listening for fragments being attached has been moved to FragmentManager.

@Override @CallSuper @NonNull void
@MainThread @NonNull boolean

This hook is called whenever an item in a context menu is selected.

@MainThread @Nullable Animation
onCreateAnimation(
    @NonNull int transit,
    @NonNull boolean enter,
    @NonNull int nextAnim
)

Called when a fragment loads an animation.

@MainThread @Nullable Animator
onCreateAnimator(
    @NonNull int transit,
    @NonNull boolean enter,
    @NonNull int nextAnim
)

Called when a fragment loads an animator.

@MainThread @Override @NonNull void

Called when a context menu for the {@code view} is about to be shown.

@MainThread @NonNull void

Initialize the contents of the Fragment host's standard options menu.

@MainThread @Nullable View
onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view.

@MainThread @NonNull void

Called when this fragment's option menu items are no longer being included in the overall options menu.

@MainThread @CallSuper @NonNull void

Called when the view previously created by onCreateView has been detached from the fragment.

@NonNull LayoutInflater
onGetLayoutInflater(@Nullable Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment.

@MainThread @NonNull void
onHiddenChanged(@NonNull boolean hidden)

Called when the hidden state (as returned by isHidden of the fragment has changed.

@UiThread @CallSuper @NonNull void
onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

This method is deprecated.

See onInflate.

@UiThread @CallSuper @NonNull void
onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

@MainThread @Override @CallSuper @NonNull void
@NonNull void
onMultiWindowModeChanged(@NonNull boolean isInMultiWindowMode)

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa.

@MainThread @NonNull boolean

This hook is called whenever an item in your options menu is selected.

@MainThread @NonNull void

This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

@NonNull void
onPictureInPictureModeChanged(@NonNull boolean isInPictureInPictureMode)

Called by the system when the activity changes to and from picture-in-picture mode.

@MainThread @NonNull void

Prepare the Fragment host's standard options menu to be displayed.

@MainThread @NonNull void
onPrimaryNavigationFragmentChanged(
    @NonNull boolean isPrimaryNavigationFragment
)

Callback for when the primary navigation state of this Fragment has changed.

@NonNull void
onRequestPermissionsResult(
    @NonNull int requestCode,
    @NonNull Array<@NonNull String> permissions,
    @NonNull Array<@NonNull int> grantResults
)

This method is deprecated.

use registerForActivityResult passing in a RequestMultiplePermissions object for the ActivityResultContract and handling the result in the callback.

@MainThread @NonNull void

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted.

@MainThread @CallSuper @NonNull void

Called when the Fragment is visible to the user.

@MainThread @NonNull void
onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view.

@MainThread @CallSuper @NonNull void
onViewStateRestored(@Nullable Bundle savedInstanceState)

Called when all saved state has been restored into the view hierarchy of the fragment.

@NonNull void

Postpone the entering Fragment transition until startPostponedEnterTransition or executePendingTransactions has been called.

final @NonNull void
postponeEnterTransition(@NonNull long duration, @NonNull TimeUnit timeUnit)

Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition.

final @MainThread @NonNull @Override ActivityResultLauncher<@NonNull I>

Register a request to Activity#startActivityForResult start an activity for result, designated by the given contract.

final @MainThread @NonNull @Override ActivityResultLauncher<@NonNull I>

Register a request to start an activity for result, designated by the given contract.

@NonNull void

Registers a context menu to be shown for the given view (multiple views can show the context menu).

final @NonNull void
requestPermissions(
    @NonNull Array<@NonNull String> permissions,
    @NonNull int requestCode
)

This method is deprecated.

use registerForActivityResult passing in a RequestMultiplePermissions object for the ActivityResultContract and handling the result in the callback.

final @NonNull FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

final @NonNull Bundle

Return the arguments supplied when the fragment was instantiated.

final @NonNull Context

Return the Context this fragment is currently associated with.

final @NonNull FragmentManager

This method is deprecated.

This has been renamed to getParentFragmentManager() to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.

final @NonNull Object

Return the host object of this fragment.

final @NonNull Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull View

Get the root view for the fragment's layout (the one returned by onCreateView).

@NonNull void

Sets whether the the exit transition and enter transition overlap or not.

@NonNull void

Sets whether the the return transition and reenter transition overlap or not.

@NonNull void

Supply the construction arguments for this fragment.

@NonNull void

When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.

@NonNull void

Sets the Transition that will be used to move Views into the initial scene.

@NonNull void

When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.

@NonNull void

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

@NonNull void
setHasOptionsMenu(@NonNull boolean hasMenu)

Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu and related methods.

@NonNull void

Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.

@NonNull void
setMenuVisibility(@NonNull boolean menuVisible)

Set a hint for whether this fragment's menu should be visible.

@NonNull void

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

@NonNull void
setRetainInstance(@NonNull boolean retain)

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

@NonNull void

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

@NonNull void

Sets the Transition that will be used for shared elements transferred into the content Scene.

@NonNull void

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack.

@NonNull void
setTargetFragment(@Nullable Fragment fragment, @NonNull int requestCode)

This method is deprecated.

Instead of using a target fragment to pass results, the fragment requesting a result should use setFragmentResultListener to register a FragmentResultListener with a {@code * requestKey} using its parent fragment manager.

@NonNull void
setUserVisibleHint(@NonNull boolean isVisibleToUser)

This method is deprecated.

If you are manually calling this method, use setMaxLifecycle instead.

@NonNull boolean

Gets whether you should show UI with rationale before requesting a permission.

@NonNull void

Call startActivity from the fragment's containing Activity.

@NonNull void

Call startActivity from the fragment's containing Activity.

@NonNull void
startActivityForResult(@NonNull Intent intent, @NonNull int requestCode)

This method is deprecated.

use registerForActivityResult passing in a StartActivityForResult object for the ActivityResultContract.

@NonNull void
startActivityForResult(
    @NonNull Intent intent,
    @NonNull int requestCode,
    @Nullable Bundle options
)

This method is deprecated.

use registerForActivityResult passing in a StartActivityForResult object for the ActivityResultContract.

@NonNull void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    @NonNull int requestCode,
    @Nullable Intent fillInIntent,
    @NonNull int flagsMask,
    @NonNull int flagsValues,
    @NonNull int extraFlags,
    @Nullable Bundle options
)

This method is deprecated.

use registerForActivityResult passing in a StartIntentSenderForResult object for the ActivityResultContract.

@NonNull void

Begin postponed transitions after postponeEnterTransition was called.

@NonNull @Override String
@NonNull void

Prevents a context menu to be shown for the given view.

From class View.OnCreateContextMenuListener
abstract @NonNull void

Constants

EXTRA_BURN_IN_PROTECTION

@NonNull
public static final @NonNull String EXTRA_BURN_IN_PROTECTION

Property in bundle passed to {@code AmbientCallback#onEnterAmbient(Bundle)} to indicate whether burn-in protection is required. When this property is set to true, views must be shifted around periodically in ambient mode. To ensure that content isn't shifted off the screen, avoid placing content within 10 pixels of the edge of the screen. Activities should also avoid solid white areas to prevent pixel burn-in. Both of these requirements only apply in ambient mode, and only when this property is set to true.

EXTRA_LOWBIT_AMBIENT

@NonNull
public static final @NonNull String EXTRA_LOWBIT_AMBIENT

Property in bundle passed to {@code AmbientCallback#onEnterAmbient(Bundle)} to indicate whether the device has low-bit ambient mode. When this property is set to true, the screen supports fewer bits for each color in ambient mode. In this case, activities should disable anti-aliasing in ambient mode.

FRAGMENT_TAG

@NonNull
public static final @NonNull String FRAGMENT_TAG

Fragment tag used by default when adding AmbientModeSupport to add ambient support to a FragmentActivity.

Public constructors

AmbientModeSupport

public AmbientModeSupport()

Constructor

Public methods

attach

@NonNull
public static AmbientModeSupport.AmbientController <T extends FragmentActivity> attach(@NonNull T activity)

Attach ambient support to the given activity. Calling this method with an Activity implementing the AmbientCallbackProvider interface will provide you with an opportunity to react to ambient events such as {@code onEnterAmbient}. Alternatively, you can call this method with an Activity which does not implement the AmbientCallbackProvider interface and that will only enable the auto-resume functionality. This is equivalent to providing (@code null} from the AmbientCallbackProvider.

Parameters
@NonNull T activity

the activity to attach ambient support to.

Returns
AmbientModeSupport.AmbientController

the associated AmbientController which can be used to query the state of ambient mode.

dump

@Override
@NonNull
public @Override void dump(
    @NonNull String prefix,
    @NonNull FileDescriptor fd,
    @NonNull PrintWriter writer,
    @NonNull Array<@NonNull String> args
)

Print the Fragments's state into the given stream.

Parameters
@NonNull String prefix

Text to print at the front of each line.

@NonNull FileDescriptor fd

The raw file descriptor that the dump is being sent to.

@NonNull PrintWriter writer

The PrintWriter to which you should dump your state. This will be closed for you after you return.

@NonNull Array<@NonNull String> args

additional arguments to the dump request.

onAttach

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onAttach(@NonNull Context context)

Called when a fragment is first attached to its context. onCreate will be called after this.

onCreate

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onCreate(@NonNull Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after onAttach and before onCreateView.

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a androidx.lifecycle.LifecycleObserver on the activity's Lifecycle, removing it when it receives the CREATED callback.

Any restored child fragments will be created before the base Fragment.onCreate method returns.

Parameters
@NonNull Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onDestroy

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onDestroy()

Called when the fragment is no longer in use. This is called after onStop and before onDetach.

onDetach

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onDetach()

Called when the fragment is no longer attached to its activity. This is called after onDestroy.

onPause

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onPause()

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

onResume

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onResume()

Called when the fragment is visible to the user and actively running. This is generally tied to Activity.onResume of the containing Activity's lifecycle.

onStop

@Override
@CallSuper
@NonNull
public @Override @CallSuper void onStop()

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