Android Studio
Added in API level 14

ComponentCallbacks2


public interface ComponentCallbacks2
implements ComponentCallbacks

android.content.ComponentCallbacks2
AbstractInputMethodService AbstractInputMethodService provides a abstract base class for input methods.  AccessibilityService Accessibility services should only be used to assist users with disabilities in using Android devices and apps.  AccountAuthenticatorActivity This class was deprecated in API level 30. Applications should extend Activity themselves. This class is not compatible with AppCompat, and the functionality it provides is not complex.  Activity An activity is a single, focused thing that the user can do.  ActivityGroup This class was deprecated in API level 13. Use the new Fragment and FragmentManager APIs instead; these are also available on older platforms through the Android compatibility package.  AliasActivity This class was deprecated in API level 30. Use <activity-alias> or subclass Activity directly.  AlternativeMessageTransportService AlternativeMessageTransportService (AMTS) allows the default SMS app to handle the sending of a message over a different transport (e.g. RCS etc.) other than the SMS or MMS.  AppContentProjectionService Service to be implemented by the application providing the MediaProjectionAppContentAppFunctionService Extend this class to implement app functions, that can be executed by AppFunctionManager.executeAppFunctionApplication Base class for maintaining global application state.  AutofillService An AutofillService is a service used to automatically fill the contents of the screen on behalf of a given user - for more information about autofill, read Autofill FrameworkCallRedirectionService This service can be implemented to interact between Telecom and its implementor for making outgoing call with optional redirection/cancellation purposes.  CallScreeningService This service can be implemented by the default dialer (see TelecomManager.getDefaultDialerPackage()) or a third party app to allow or disallow incoming calls before they are shown to a user.  CameraPrewarmService Extend this class to implement a camera prewarm service.  CarrierMessagingClientService If the default SMS app has a service that extends this class, the system always tries to bind it so that the process is always running, which allows the app to have a persistent connection to the server.  CarrierMessagingService A service that receives calls from the system when new SMS and MMS are sent or received.  CarrierService A service that exposes carrier-specific functionality to the system.  ChooserTargetService This class was deprecated in API level 30. For publishing direct share targets, please follow the instructions in https://developer.android.com/training/sharing/receive.html#providing-direct-share-targets instead.  CloudMediaProvider Base class for a cloud media provider.  CompanionDeviceService A service that receives calls from the system with device events.  ConditionProviderService This class was deprecated in API level 29. Instead of using an automatically bound service, use android.app.NotificationManager.setAutomaticZenRuleState(String,Condition) to tell the system about the state of your rule. In order to maintain a link from Settings to your rule configuration screens, provide a configuration activity that handles NotificationManager.ACTION_AUTOMATIC_ZEN_RULE on your AutomaticZenRule via android.app.AutomaticZenRule.setConfigurationActivity(ComponentName).  ConnectionService An abstract service that should be implemented by any apps which either: Can make phone calls (VoIP or otherwise) and want those calls to be integrated into the built-in phone app.  ContentProvider Content providers are one of the primary building blocks of Android applications, providing content to applications.  ControlsProviderService Service implementation allowing applications to contribute controls to the System UI.  CredentialProviderService Service to be extended by credential providers, in order to return user credentials to the framework.  DataMigrationToPccService Base class for a service that handles data migration to the Private Compute Core (PCC) storage of an application.  DeviceAdminService Base class for a service that device owner/profile owners can optionally have.  DialogFragment This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.  DocumentsProvider Base class for a document provider.  DreamService Extend this class to implement a custom dream (available to the user as a "Daydream").  ExpandableListActivity This class was deprecated in API level 30. Use RecyclerView or use ExpandableListView directly  Fragment This class was deprecated in API level 28. Use the Jetpack Fragment Library Fragment for consistent behavior across all devices and access to Lifecycle.  HostApduService HostApduService is a convenience Service class that can be extended to emulate an NFC card inside an Android service component.  HostNfcFService HostNfcFService is a convenience Service class that can be extended to emulate an NFC-F card inside an Android service component.  InCallService This service is implemented by an app that wishes to provide functionality for managing phone calls.  InputMethodService InputMethodService provides a standard implementation of an InputMethod, which final implementations can derive from and customize.  IntentService This class was deprecated in API level 30. IntentService is subject to all the background execution limits imposed with Android 8.0 (API level 26). Consider using WorkManager instead.  IsolatedService This class was deprecated in API level 37. The ODP APIs are deprecated and will not be supported in future Android releases. There is no direct replacement API available. Developers currently integrated with these APIs must cease further integration efforts. For comprehensive details regarding this deprecation and the future roadmap of Privacy Sandbox on Android, please consult the official Privacy Sandbox developer documentation and announcements: https://privacysandbox.google.com  JobService Entry point for the callback from the JobSchedulerLauncherActivity This class was deprecated in API level 30. Applications can implement this UI themselves using RecyclerView and android.content.pm.PackageManager.queryIntentActivities(Intent,int)  ListActivity This class was deprecated in API level 30. Use ListFragment or RecyclerView to implement your Activity instead.  ListFragment This class was deprecated in API level 28. Use the Support Library ListFragment for consistent behavior across all devices and access to Lifecycle.  MediaBrowserService Base class for media browser services.  MediaRoute2ProviderService Base class for media route provider services.  MediaSession2Service This class was deprecated in API level 37. Use the Media3 support library's androidx.media3.session.MediaSessionService instead.  MidiDeviceService A service that implements a virtual MIDI device.  MidiUmpDeviceService A service that implements a virtual MIDI device for Universal MIDI Packets (UMP).  MockApplication This class was deprecated in API level 24. Use a mocking framework like Mockito. New tests should be written using the Android Testing Support Library.  MockContentProvider Mock implementation of ContentProvider.  NativeActivity Convenience for implementing an activity that will be implemented purely in native code.  NotificationListenerService A service that receives calls from the system when new notifications are posted or removed, or their ranking changed.  OffHostApduService

OffHostApduService is a convenience Service class that can be extended to describe one or more NFC applications that are residing off-host, for example on an embedded secure element or a UICC.  PccService Abstract base class for a PCC service that receives data from other components.  PreferenceActivity This class was deprecated in API level 29. Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.  PreferenceFragment This class was deprecated in API level 28. Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.  PrintService

This is the base class for implementing print services.  QuickAccessWalletService A QuickAccessWalletService provides a list of WalletCards shown in the Quick Access Wallet.  RecognitionService This class provides a base class for recognition service implementations.  RemoteViewsService The service to be connected to for a remote adapter to request RemoteViews.  SearchRecentSuggestionsProvider This superclass can be used to create a simple search suggestions provider for your application.  Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.  SettingInjectorService Dynamically specifies the summary (subtitle) and enabled status of a preference injected into the list of app settings displayed by the system settings app

For use only by apps that are included in the system image, for preferences that affect multiple apps.  SettingsPreferenceService Base class for a service that exposes its settings preferences to external access.  SliceProvider This class was deprecated in API level 35. Slice framework has been deprecated, it will not receive any updates from ERROR(/android.os.Build.VANILLA_ICE_CREAM) and forward. If you are looking for a framework that sends displayable data from one app to another, consider using AppSearchManager.  SpellCheckerService SpellCheckerService provides an abstract base class for a spell checker.  TabActivity This class was deprecated in API level 13. New applications should use Fragments instead of this class; to continue to run on older devices, you can use the v4 support library which provides a version of the Fragment API that is compatible down to Build.VERSION_CODES.DONUT.  TextToSpeechService Abstract base class for TTS engine implementations.  TileService A TileService provides the user a tile that can be added to Quick Settings.  TvAdService The TvAdService class represents a TV client-side advertisement service.  TvInputService The TvInputService class represents a TV input or source such as HDMI or built-in tuner which provides pass-through video or broadcast TV programs.  TvInteractiveAppService A TV interactive application service is a service that provides runtime environment and runs TV interactive applications.  VisualVoicemailService This service is implemented by dialer apps that wishes to handle OMTP or similar visual voicemails.  VoiceInteractionService Top-level service of the current global voice interactor, which is providing support for hotwording, the back-end of a VoiceInteractor, etc.  VoiceInteractionSession An active voice interaction session, providing a facility for the implementation to interact with the user in the voice interaction layer.  VoiceInteractionSessionService An active voice interaction session, initiated by a VoiceInteractionServiceVpnService VpnService is a base class for applications to extend and build their own VPN solutions.  VrListenerService A service that is bound from the system while running in virtual reality (VR) mode.  WallpaperService A wallpaper service is responsible for showing a live wallpaper behind applications that would like to sit on top of it.  WebViewFragment This class was deprecated in API level 28. Manually call WebView.onPause() and WebView.onResume() 



Callbacks for app state transitions that can be used to improve background memory management. This interface is available in all application components (Activity, Service, ContentProvider, and Application).

You should implement onTrimMemory(int) to release memory when your app goes to background states. Doing so helps the system keep your app's process cached in memory for longer, such that the next time that the user brings your app to the foreground, the app will perform a warm or hot start, resuming faster and retaining state.

Trim memory levels and how to handle them

Apps that continue to do work for the user when they're not visible can respond to the TRIM_MEMORY_UI_HIDDEN callback by changing their behavior to favor lower memory usage. For example, a music player may keep full-sized album art for all tracks in the currently playing playlist as Bitmaps cached in memory. When the app is backgrounded but music playback continues, the app can change the caching behavior to cache fewer, or smaller, Bitmaps in memory.

The ordinal values for trim levels represent an escalating series of memory pressure events, with incrementing values accordingly. More states may be added in the future. As such, it's important not to check for specific values, but rather check if the level passed to onTrimMemory(int) is greater than or equal to the levels that your application handles. For example:

public void onTrimMemory(int level) {
     if (level >= TRIM_MEMORY_BACKGROUND) {
         // Release any resources that can be rebuilt
         // quickly when the app returns to the foreground
         releaseResources();
     } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
         // Release UI-related resources
         releaseUiResources();
     }
 }
 

Note: the runtime may invoke Garbage Collection (GC) in response to application state changes. There is no need to explicitly invoke GC from your app.

Summary

Constants

int TRIM_MEMORY_BACKGROUND

Level for onTrimMemory(int): the process has gone on to the LRU list.

int TRIM_MEMORY_COMPLETE

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_MODERATE

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_RUNNING_CRITICAL

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_RUNNING_LOW

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_RUNNING_MODERATE

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_UI_HIDDEN

Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so.

Public methods

abstract void onTrimMemory(int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.

Inherited methods

Constants

TRIM_MEMORY_BACKGROUND

Added in API level 14
public static final int TRIM_MEMORY_BACKGROUND

Level for onTrimMemory(int): the process has gone on to the LRU list. This is a good opportunity to clean up resources that can efficiently and quickly be re-built if the user returns to the app.

Constant Value: 40 (0x00000028)

TRIM_MEMORY_COMPLETE

Added in API level 14
Deprecated in API level 35
public static final int TRIM_MEMORY_COMPLETE

This constant was deprecated in API level 35.
Apps are not notified of this level since API level 34

Level for onTrimMemory(int): the process is nearing the end of the background LRU list, and if more memory isn't found soon it will be killed.

Constant Value: 80 (0x00000050)

TRIM_MEMORY_MODERATE

Added in API level 14
Deprecated in API level 35
public static final int TRIM_MEMORY_MODERATE

This constant was deprecated in API level 35.
Apps are not notified of this level since API level 34

Level for onTrimMemory(int): the process is around the middle of the background LRU list; freeing memory can help the system keep other processes running later in the list for better overall performance.

Constant Value: 60 (0x0000003c)

TRIM_MEMORY_RUNNING_CRITICAL

Added in API level 16
Deprecated in API level 35
public static final int TRIM_MEMORY_RUNNING_CRITICAL

This constant was deprecated in API level 35.
Apps are not notified of this level since API level 34

Level for onTrimMemory(int): the process is not an expendable background process, but the device is running extremely low on memory and is about to not be able to keep any background processes running. Your running process should free up as many non-critical resources as it can to allow that memory to be used elsewhere. The next thing that will happen after this is ComponentCallbacks.onLowMemory() called to report that nothing at all can be kept in the background, a situation that can start to notably impact the user.

Constant Value: 15 (0x0000000f)

TRIM_MEMORY_RUNNING_LOW

Added in API level 16
Deprecated in API level 35
public static final int TRIM_MEMORY_RUNNING_LOW

This constant was deprecated in API level 35.
Apps are not notified of this level since API level 34

Level for onTrimMemory(int): the process is not an expendable background process, but the device is running low on memory. Your running process should free up unneeded resources to allow that memory to be used elsewhere.

Constant Value: 10 (0x0000000a)

TRIM_MEMORY_RUNNING_MODERATE

Added in API level 16
Deprecated in API level 35
public static final int TRIM_MEMORY_RUNNING_MODERATE

This constant was deprecated in API level 35.
Apps are not notified of this level since API level 34

Level for onTrimMemory(int): the process is not an expendable background process, but the device is running moderately low on memory. Your running process may want to release some unneeded resources for use elsewhere.

Constant Value: 5 (0x00000005)

TRIM_MEMORY_UI_HIDDEN

Added in API level 14
public static final int TRIM_MEMORY_UI_HIDDEN

Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so. Large allocations with the UI should be released at this point to allow memory to be better managed.

Constant Value: 20 (0x00000014)

Public methods

onTrimMemory

Added in API level 14
public abstract void onTrimMemory (int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process. You should never compare to exact values of the level, since new intermediate values may be added -- you will typically want to compare if the value is greater or equal to a level you are interested in.

To retrieve the processes current trim level at any point, you can use ActivityManager.getMyMemoryState(RunningAppProcessInfo).

Parameters level int: The context of the trim, giving a hint of the amount of trimming the application may like to perform.
Value is one of the following: