Android studio bundle что это

Методы активности

Методы

В статье приведены только часть методов. Остальные изучайте самостоятельно через документацию.

При переходе активности от одного состояния к другому, она получает уведомления через защищенные методы:

  • protected void onCreate(Bundle savedInstanceState);
  • protected void onStart();
  • protected void onRestart();
  • protected void onResume();
  • protected void onPause();
  • protected void onStop();
  • protected void onDestroy()

Из перечисленных методов в вашем классе обязательно должен быть метод onCreate(), которая задаёт начальную установку параметров при инициализации активности. Вторым по популярности является метод onPause(), используемый для сохранения пользовательских настроек активности и подготовиться к прекращению взаимодействия с пользователем.

При реализации любого из этих методов необходимо всегда сначала вызывать версию этого метода из суперкласса. Например:

Семь перечисленных методов определяют весь жизненный цикл активности. Есть три вложенных цикла, которые вы можете отслеживать в классе активности:

  • полное время жизни (entire lifetime) — время с момента первого вызова метода onCreate() до вызова onDestroy(). Активность делает всю начальную установку своего глобального состояния в методе onCreate() и освобождает все остающиеся ресурсы в onDestroy(). Например, если активность порождает дополнительный поток, выполняющийся в фоновом режиме, можно создать этот поток в методе onCreate() и затем остановить поток в методе onDestroy();
  • видимое время жизни (visible lifetime) — время между вызовом метода onStart() и вызовом onStop(). В это время пользователь может видеть окно активности на экране, хотя окно может не быть на переднем плане и может не взаимодействовать с пользователем. Между этими двумя методами вы можете поддерживать в коде ресурсы, которые необходимы, чтобы отображать активность пользователю;
  • активное время жизни (foreground lifetime) — время между вызовами onResume() и onPause(). В это время окно активности находится на переднем плане и взаимодействует с пользователем. Активность в процессе работы приложения может часто переходить между состояниями active и paused, поэтому код в этих двух методах должен быть или небольшим по объему (чтобы не замедлять работу приложения во время выполнения), или порождать дополнительные потоки, если требуется выполнение задач, занимающих длительное время.

Можно написать код с заглушками для методов внутри Активности, которые обрабатывают изменения состояний. Комментарии к каждой такой заглушке описывают действия, которые нужно учитывать при обработке этих событий.

Как видно из кода, переопределяя эти обработчики, вы всегда должны вызывать одноимённые методы родительского класса.

Методы жизненного цикла описаны в отдельной статье. Здесь их опишем кратко и рассмотрим другие методы.

Метод addContentView()

Метод addContentView() добавляет компонент к уже существующей разметке. Пример смотрите здесь.

Метод findViewById()

Метод findViewById() позволяет получить ссылку на View, которая размещена в разметке через его идентификатор.

Если вы используете фрагменты, то когда они загружаются в активность, то компоненты, входящие в состав фрагмента, становятся частью иерархии активности. И вы можете использовать метод findViewById() для получения ссылки к компоненту фрагмента.

Не путать с одноимённым методом для класса View.

Метод finish()

C помощью метода finish() можно завершить работу активности. Если приложение состоит из одной активности, то этого делать не следует, так как система сама завершит работу приложения. Если же приложение содержит несколько активностей, между которыми нужно переключаться, то данный метод позволяет экономить ресурсы.

Метод getFragmentManager()

Каждая активность включает в себя Менеджер фрагментов для управления фрагментами, если они используются. Метод getFragmentManager() позволяет получить доступ к данному менеджеру. На сайте есть отдельные статьи, посвящённые фрагментам.

Метод getParentActivityIntent()

Возвращает намерение, которое может запускать активность, являющей родительской. Родительская активность прописывается в манифесте. Вы можете переопределить данное намерение для своих целей. Метод появился в API 16.

Метод onActivityResult()

Дочерняя активность может произвольно возвратить назад объект Intent, содержащий любые дополнительные данные. Вся эта информация в родительской активности появляется через метод обратного вызова Activity.onActivityResult(), наряду с идентификатором, который она первоначально предоставила.

Если дочерняя активность завершится неудачно или будет закрыта пользователем без подтверждения ввода через кнопку Back, то родительская активность получит результат с кодом RESULT_CANCELED.

Метод принимает несколько параметров:

  • Код запроса — тот код, который использовался для запуска дочерней активности, возвращающий результат.
  • Результирующий код — код результата, поступающий от дочерней активности, как правило, RESULT_OK или RESULT_CANCELED
  • Данные — намерение может включать в себя различные данные в виде параметра extras внутри намерения.

Метод onBackPressed()

Метод, позволяющий отследить нажатине на кнопку Back. Появился в Android 2.0 (API 5). Пример использования можно посмотреть в статье Кнопка Back: Вы уверены, что хотите выйти из программы?.

Метод onConfigurationChanged()

Метод, который вызывается при изменении конфигурации устройства. Если в манифесте были установлены специальные параметры у атрибута android:configChanges, то данный метод не будет вызван.

Метод onKeyShortcut()

Метод onPostCreate()

Новый метод, который появился в API 21. Он вызывается позже onCreate() и в нём можно получить значения размеров компонентов, которые недоступны при построении интерфейса в методе onCreate().

Метод overridePendingTransition()

Метод overridePendingTransition() позволяет задать анимацию при переходе от одной активности к другой. Пример смотрите здесь.

Метод onRestoreInstanceState()

У метода onRestoreInstanceState() есть такой же параметр Bundle, как у onCreate(), и вы можете восстанавливать сохранённые значения из метода onSaveInstanceState(). Во многих случаях это пример личных предпочтений, какой из двух методов использовать для восстановления данных.

Метод вызывается после метода onStart(). Система вызывает метод onRestoreInstanceState() только в том случае, если имеются сохранённые данные для восстановления. Таким образом вам не нужно проверять Bundle на null, как в методе onCreate():

Метод onSaveInstanceState()

Когда система завершает активность в принудительном порядке, чтобы освободить ресурсы для других приложений, пользователь может снова вызвать эту активность с сохранённым предыдущим состоянием. Чтобы зафиксировать состояние активности перед её уничтожением, в классе активности необходимо реализовать метод onSaveinstancestate().

Сам метод вызывается прямо перед методом onPause(). Он предоставляет возможность сохранять состояние пользовательского интерфейса активности в объект Bundle, который потом будет передаваться в методы onCreate() и onRestoreInstanceState(). В объект Bundle можно записать параметры, динамическое состояние активности как пары «ключ-значение». Когда активность будет снова вызвана, объект Bundle передаётся системой в качестве параметра в методы onCreate() и onRestoreInstanceState(), которые вызываются после onStart(), чтобы один из них или они оба могли установить активность в предыдущее состояние. Прежде чем передавать изменённый параметр Bundle в обработчик родительского класса, сохраните значения с помощью методов putXXX() и восстановите с помощью getXXX().

Используйте обработчик onSaveInstanceState() для сохранения состояния интерфейса (например, состояния флажков, текущего выделенного элемента или введенных, но не сохранённых данных), чтобы объект Activity при следующем входе в активное состояние мог вывести на экран тот же UI. Рассчитывайте, что перед завершением работы процесса во время активного состояния будут вызваны обработчики onSaveInstanceState и onPause.

Читайте также:  Радмин впн для андроид

В отличие от базовых методов, методы onSaveInstanceState() и onRestoreInstanceState() не относятся к методам жизненного цикла активности. Система будет вызывать их не во всех случаях. Например, Android вызывает onSaveinstancestate() прежде, чем активность становится уязвимой к уничтожению системой, но не вызывает его, когда экземпляр активности разрушается пользовательским действием (при нажатии клавиши BACK). В этом случае нет никаких причин для сохранения состояния активности.

Метод onSaveInstanceState() вызывается системой в случае изменения конфигурации устройства в процессе выполнения приложения (например, при вращении устройства пользователем или выдвижении физической клавиатуры устройства.

Поскольку метод onSaveinstanceState() вызывается не во всех случаях, его необходимо использовать только для сохранения промежуточного состояния активности. Для сохранения данных лучше использовать метод onPause().

Этот обработчик будет срабатывать всякий раз, когда жизненный цикл активности начнёт подходить к концу, но только в том случае, если её работа не будет завершена явно (при вызове метода finish()). Вследствие этого обработчик используется для проверки целостности состояния активности между активными жизненными циклами одиночной пользовательской сессии.

Сохранённый параметр Bundle передается методам onRestoreInstanceState() и onCreate(), если приложение принудительно перезапускается на протяжении сессии. В листинге показано, как извлечь значения из этого параметра и использовать их для обновления состояния экземпляра активности.

В API 28 метод вызывается после метода onStop(), в ранних версиях до метода onStop().

Метод onUserLeaveHint()

Позволяет отследить нажатие кнопки Home

Метод requestWindowFeature()

Метод позволяет задействовать дополнительные возможности для активности, например, выводить экран активности без заголовка. Примеры смотрите здесь.

Метод onWindowFocusChanged()

Метод позволяет определить момент получения фокуса вашим приложением.

Метод может быть полезен, так как он срабатывает позже метода onCreate(). Например, для вычисления размеров кнопки на экране этот метод предпочтительнее, так как уже известно, что все элементы загрузились и доступны, тогда как в onCreate() могут возвратиться пустые значения ширины и высоты кнопки. Пример использования.

Метод setContentView()

Изначально экран активности пуст. Чтобы разместить пользовательский интерфейс, необходимо вызвать метод setContentView(). У метода есть две перегруженные версии. Вы можете передать в параметре либо экземпляр компонента (View), либо идентификатор ресурса (наиболее распространённый способ).

Пример с использованием экземпляра компонента:

В этом примере вы увидите на экране текстовое поле с текстом. Но при таком способе вы можете использовать только один компонент. А если экран состоит из множества кнопок и прочих элементов управления, то нужно использовать разметку.

Метод setFeatureDrawableResource()

С помощью данного метода можно вывести значки в правой части заголовка. Смотри пример.

Метод setRequestedOrientation()

Метод позволяет программно изменить ориентацию экрана. Пример использования.

Метод startActivity()

Чтобы запустить новую активность, используется метод startActivity(Intent). Этот метод принимает единственный параметр — объект Intent, описывающий активность, которая будет запускаться. Смотри пример Activity.

Метод startActivityForResult()

Иногда требуется вернуть результат активности, когда она закрывается. Например, можно запустить активность, которая позволяет пользователю выбирать человека в списке контактов. При закрытии активность возвращает данные человека, который был выбран: его полное имя и телефон. В этом случае необходимо вызвать метод startActivityForResult()

Метод startActivityForResult(Intent, int) со вторым параметром, идентифицирующим запрос позволяет возвращать результат. Когда дочерняя активность закрывается, то в родительской активности срабатывает метод onActivityResult(int, int, Intent), который содержит возвращённый результат, определённый в родительской активности.

Метод setResult()

Когда активность завершится, вы можете вызвать метод setResult(int), чтобы возвратить данные назад в родительскую активность (до метода finish()). Этот метод возвращает код результата закрытия активности, который может быть стандартными результатами Activity.RESULT_CANCELED, Activity.RESULT_OK или определяемым пользователем результатом RESULT_FiRST_USER (можете придумать любую константу с целочисленным значением).

Если в дочерней активности есть кнопка отмены, то код может быть следующим:

Если метод finish() вызвать раньше метода setResult(), то результирующий код установится в RESULT_CANCELED автоматически, а возвращённое намерение покажет значение null.

Источник

Bundle Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

A mapping from String keys to various Parcelable values.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs a new, empty Bundle.

Constructs a new, empty Bundle.

Constructs a new, empty Bundle.

Constructs a new, empty Bundle.

Constructs a new, empty Bundle.

Properties

Returns the runtime class of this Object .

(Inherited from Object) ClassLoader

Return the ClassLoader currently associated with this Bundle.

An unmodifiable Bundle that is always #isEmpty() empty .

The handle to the underlying Android instance.

(Inherited from Object) HasFileDescriptors

Reports whether the bundle contains any parcelled file descriptors.

Returns true if the mapping of this Bundle is empty, false otherwise.

JniIdentityHashCode (Inherited from Object) JniPeerMembers PeerReference (Inherited from Object) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

(Inherited from BaseBundle) ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

(Inherited from BaseBundle)

Methods

Removes all elements from the mapping of this Bundle.

Clones the current Bundle.

Returns true if the given key is contained in the mapping of this Bundle.

Make a deep copy of the given bundle.

Report the nature of this Parcelable’s contents

Dispose() (Inherited from Object) Dispose(Boolean) (Inherited from Object) Equals(Object)

Indicates whether some other object is «equal to» this one.

(Inherited from Object) Get(String)

Returns the entry with the given key as an object.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or false if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Читайте также:  Android list targets no targets

Returns the value associated with the given key, or (byte) 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or (byte) 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or (char) 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or (char) 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or 0.0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or 0.

Returns the value associated with the given key, or 0.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns a hash code value for the object.

(Inherited from Object) GetInt(String)

Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or 0L if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or (short) 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or (short) 0 if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Читайте также:  Remote fingerprint unlock pro apk для андроид

Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object) KeySet()

Returns a Set containing the Strings used as keys in this Bundle.

Wakes up a single thread that is waiting on this object’s monitor.

(Inherited from Object) NotifyAll()

Wakes up all threads that are waiting on this object’s monitor.

(Inherited from Object) PutAll(Bundle)

Inserts all mappings from the given Bundle into this Bundle.

Inserts all mappings from the given PersistableBundle into this BaseBundle.

(Inherited from BaseBundle) PutBinder(String, IBinder)

Inserts an IBinder value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a Boolean value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a boolean array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a Bundle value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a byte value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a byte array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a char value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a char array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a CharSequence value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a CharSequence value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a CharSequence array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a CharSequence array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts an ArrayList value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a double value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a double array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a float value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a float array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts an int value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts an int array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts an ArrayList value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a long value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a long array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts an array of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a List of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a Serializable value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a short value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a short array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a Size value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a SizeF value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a SparceArray of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a String value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts a String array value into the mapping of this Bundle, replacing any existing value for the given key.

Inserts an ArrayList value into the mapping of this Bundle, replacing any existing value for the given key.

Reads the Parcel contents into this Bundle, typically in order for it to be passed through an IBinder connection.

Removes any entry with the given key from the mapping of this Bundle.

Changes the ClassLoader this Bundle uses when instantiating objects.

Sets the Handle property.

(Inherited from Object) Size()

Returns the number of mappings contained in this Bundle.

Returns a string representation of the object.

(Inherited from Object) UnregisterFromRuntime() (Inherited from Object) Wait()

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64, Int32)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) WriteToParcel(Parcel, ParcelableWriteFlags)

Writes the Bundle contents to a Parcel, typically in order for it to be passed through an IBinder connection.

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Оцените статью