- Запуск другой Activity — второго окна android-приложения
- В этом уроке
- Вы также должны прочитать
- Ответить на кнопку Отправить
- Создать Intent
- Отправка intent в другие приложения
- Запуск второй Activity
- Создание второй Activity
- Для создания новой Activity в Android Studio:
- Для создания новой Activity в Eclipse:
- Как я могу вернуться к родительской активности правильно?
- Android studio get parent activity
Запуск другой Activity — второго окна android-приложения
В этом уроке
Вы также должны прочитать
После завершения предыдущего урока, у вас есть приложение, которое показывает активити (один экран) с текстовым полем и кнопкой. В этом уроке вы добавим код к MainActivity , который запустит новую активити , когда пользователь нажмет на кнопку Отправить..
Ответить на кнопку Отправить
Чтобы ответить на событие нажатия кнопки, откройте fragment_main.xml файла макета и добавьте android:onClick атрибут к элементу:
android:onClick значение атрибута, «sendMessage» , это имя метода в вашей активити , который система вызывает когда пользователь нажимает кнопку.
Откройте MainActivity класс (расположенный в каталоге проекта src/ ) и добавьте соответствующий метод:
Чтобы система смогла найти этот метод с именем, заданным в android:onClick , сигнатура должна быть именно такой, как вы видели. В частности, метод должен:
- Быть public
- Имейте void в качестве возвращаемого значения
- Иметь View в качестве единственного параметра (это будет View , на котором нажали)
Далее, вы заполните этот метод, чтобы прочитать содержимое текстового поля и доставить этот текст в другую активити .
Создать Intent
Intent это объект, который обеспечивает связывание отдельных компонент во время выполнения (например, двух активити ). Intent представляет «намерение что-то сделать». Вы можете использовать интент для широкого круга задач, но чаще всего они используются, чтобы начать другую активити .
Внутри sendMessage() метода, создайте Intent для запуска активити под названием DisplayMessageActivity :
Для этого требуется импортировать Intent класс:
Полезный совет: В Eclipse, нажмите Ctrl + Shift + O для импортирования недостающих классов (Cmd + Shift + O на Mac). В Android Studio команда для импорта Alt+Enter.
Конструктор, используемый здесь принимает два параметра:
- Context в качестве первого параметра( this используется, поскольку Activity класс является подклассом Context )
- Class компонента приложения, в который система должна доставить Intent (в данном случае активность, которая должна быть запущена)
Отправка intent в другие приложения
Intent, созданный в этом уроке считается явным, поскольку Intent указывает точный компонент приложения, в которое интент следует отправить. Тем не менее, интенты также могут быть неявными, в этом случае Intent не указывает нужный компонент, позволяя любой программе установленной на устройстве отвечать на интенты, пока она удовлетворяет спецификациям мета-данных действия, задаваемыми в различных Intent параметрах. Для получения дополнительной информации читайте курс Взаимодействие с другими приложениями.
Примечание: Ссылка на DisplayMessageActivity вызовет ошибку, если вы используете интегрированную среду разработки, такую как Eclipse например, потому что класс еще не существует. Игнорируйте ошибку на данный момент; вы скоро создадите класс.
Intent не только позволяет начать другую Activity, но также может выполнять связь данных в Activity. В sendMessage() методе, используйте findViewById() для получения EditText элемента и добавьте его текстовое значение в Intent:
Примечание: Вам необходим оператор импорта для android.widget.EditText . Вы определите EXTRA_MESSAGE константу буквально сейчас.
Intent может нести коллекцию различных типов данных в виде пары ключ-значение, называемых Extras. Метод putExtra() принимает имя ключа в первом параметре и значение во втором параметре.
Для того, чтобы Activity смогла запросить дополнительные данные, вы должны определить ключ для дополнений вашего интента, используя общедоступную константу. Так что добавьте EXTRA_MESSAGE определение в начало MainActivity класса:
Вообще это хорошая практика, определять ключи для Intent Extras используя имя пакета вашего приложения в качестве префикса. Это гарантирует, что они уникальны, в случае когда ваше приложение взаимодействует с другими приложениями.
Запуск второй Activity
Для запуска активити, вызовите startActivity() и передайте в него ваш Intent . Система получает этот вызов и запускает экземпляр Activity указанный в Intent .
С помощью этого нового кода, полный sendMessage() метод, который вызывается кнопкой Отправить теперь выглядит следующим образом:
Теперь вам нужно создать DisplayMessageActivity класс для того, чтобы это работало.
Создание второй Activity
Для создания новой Activity в Android Studio:
В главном меню выберите File>New>Activity>Blank Activity.
Заполните поля в окне мастера создания активити:
- Activity Name: DisplayMessageActivity
- Layout Name: activity_display_message
- Title: Моё сообщение
- Hierarchial Parent: com.example.myfirstapp.MainActivity
Остальные поля оставьте по умолчанию. Нажмите Finish.
Для создания новой Activity в Eclipse:
- Нажмите New
на панели инструментов.
- В появившемся окне, откройте Android папку и выберите Android Activity. Нажмите Next.
- Выберите BlankActivity и нажмите Next.
- Заполните информацию о Activity:
- Project: MyFirstApp
- Activity Name: DisplayMessageActivity
- Layout Name: activity_display_message
- Fragment Layout Name: fragment_display_message
- Title: Моё сообщение
- Hierarchial Parent: com.example.myfirstapp.MainActivity
- Navigation Type: None
Нажмите Finish.
Рисунок 1. Мастер новой активити в Eclipse.
Если вы используете инструменты командной строки, создайте новый файл с именем DisplayMessageActivity.java в проекте в src/ каталоге, рядом с оригиналом MainActivity.java файлом.
Откройте DisplayMessageActivity.java файл. Если вы использовали Android Studio или Eclipse для создания этой Activity:
- Класс уже включает в себя реализацию требуемого onCreate() метода. Вы обновите реализацию этого метода позже.
- Есть также реализация onCreateOptionsMenu() метода, но вам это не будет нужно в данном приложении, так что вы можете удалить его.
- Есть также реализация onOptionsItemSelected() , который обрабатывает поведение панели действий для кнопки Вверх . Оставьте его как есть.
- Может быть также PlaceholderFragment класс, который расширяет Fragment . Вам не нужен будет этот класс в окончательном варианте этой активити .
Фрагменты разбивают функциональность приложений и пользовательский интерфейс на модули, которые можно будет повторно использовать. Для более подробной информации о фрагментах см.Руководство по Фрагментам. Окончательный вариант этой активити не использует фрагменты.
Примечание: Ваша активити может выглядеть иначе, если вы не использовали последнюю версию ADT плагина. Убедитесь, что вы установили последнюю версию ADT плагина для завершения этого курса.
DisplayMessageActivity класс должен выглядеть следующим образом:
Источник
Как я могу вернуться к родительской активности правильно?
У меня есть 2 действия (A и B) в приложении для Android и я использую намерение перейти от действия A к активности B. Использование parent_activity включено:
Я также использую тему, которая содержит кнопку UP.
Поэтому после того, как я вызвал активность, BI может использовать UP-кнопку, чтобы вернуться к активности A. Проблема в том, что приложение, похоже, снова вызывает функцию onCreate () активности A, и это не то поведение, в котором я нуждаюсь. Мне нужна активность А, чтобы выглядеть так же, как она выглядела раньше, чем я назвал деятельность Б.
Есть ли способ достичь этого?
Я не написал код для запуска активности B из активности A. Я думаю, что это автогенерируется eclipse.
Класс B выглядит так:
Вы объявили активность A стандартным launchMode в манифестах Android. Согласно документации , это означает следующее:
Система всегда создает новый экземпляр действия в целевой задаче и направляет на нее намерение.
Поэтому система вынуждена воссоздавать активность A (то есть вызывать onCreate ), даже если стек задачи обрабатывается правильно.
Чтобы исправить эту проблему, вам нужно изменить манифест, добавив в объявление активности A следующий атрибут:
Примечание: call finish() (как предложено ранее как решение) работает только тогда, когда вы полностью уверены, что экземпляр действия B завершает жизнь поверх экземпляра активности A. В более сложных рабочих процессах (например, запуск активности B из Уведомление), это может быть не так, и вы должны правильно запустить активность A из B.
Обновленный ответ: Up Navigation Design
Вы должны объявить, какая деятельность является соответствующим родителем для каждого вида деятельности. Это позволяет системе упростить навигационные шаблоны, такие как Up, потому что система может определять логическую родительскую активность из файла манифеста.
Для этого вам нужно объявить свою родительскую активность в теге Activity с атрибутом
С объявленной таким образом родительской активностью вы можете перейти к соответствующему родительскому элементу, как показано ниже,
Поэтому, когда вы вызываете NavUtils.navigateUpFromSameTask(this); Этот метод завершает текущую деятельность и запускает (или возобновляет) соответствующую родительскую активность. Если целевая родительская активность находится в FLAG_ACTIVITY_CLEAR_TOP стеке задачи, она FLAG_ACTIVITY_CLEAR_TOP как определено FLAG_ACTIVITY_CLEAR_TOP .
И чтобы отобразить кнопку «Вверх», вы должны объявить setDisplayHomeAsUpEnabled():
Старый ответ: (Без навигации вверх, по умолчанию Назад)
Это происходит только в том случае, если вы снова запускаете Activity A из Activity B.
Использование функции startActivity() .
Вместо этого из Activity A запустите Activity B, используя startActivityForResult() и переопределите onActivtyResult() в onActivtyResult() A.
Теперь в Activity B просто вызовите finish() на кнопке Up. Итак, теперь вы onActivityResult() на ActivityA’s onActivityResult() без создания Activity A снова ..
У меня была почти такая же настройка, которая привела к такому же нежелательному поведению. Для меня это работало, чтобы добавить следующий атрибут к активности A в Manifest.xml моего приложения:
андроид: launchMode = «singleTask»
Хотя старый вопрос, вот еще одно (самое лучшее и лучшее) решение, поскольку все предыдущие ответы не работали для меня, так как я отключил активность B от виджета .
Лучший способ добиться этого – использовать две вещи: call:
Теперь, чтобы это сработало, вам нужно, чтобы ваше состояние файла манифеста указывало, что активность A имеет родительскую активность B. Родительская активность ничего не нуждается. В версии 4 и выше вы получите приятную обратную стрелку без дополнительных усилий (это можно сделать и в более низких версиях, а также с небольшим кодом, я опишу ниже). Вы можете установить эти данные на вкладке manifest-> application В графическом интерфейсе (прокрутите вниз до имени родительской активности и поместите его вручную)
Если вы хотите поддерживать версию ниже версии 4, вам также необходимо включить метаданные. Щелкните правой кнопкой мыши на активности, add-> meta data, name = android.support.PARENT_ACTIVITY и value = your.full.activity.name
Для получения хорошей стрелки в более низких версиях:
Обратите внимание, что вам понадобится поддержка версии 7 библиотеки поддержки, чтобы все это работало, но это того стоит!
У меня была аналогичная проблема с использованием android 5.0 с именем плохой родительской активности
Я удалил com.example.myfirstapp из имени родительской активности и работал правильно
Я пробовал android:launchMode=»singleTask» , но это не помогло. Работал для меня с помощью android:launchMode=»singleInstance»
Добавляя к ответу @ LorenCK, измените
К приведенному ниже коду, если ваша деятельность может быть инициирована из другого действия, и это может стать частью задачи, запущенной каким-либо другим приложением
Это запустит новую задачу и запустит родительскую активность Activity, которую вы можете определить в манифесте, как показано ниже в версии Min SDK
Или используйте parentActivityName если его> 15
Добавить в свою информацию о манифесте активности с атрибутом
Хорошо работает для меня
Что сработало для меня, было добавление:
К TheRelevantActivity.java и теперь он работает как ожидалось
И да, не забудьте добавить:
getSupportActionbar.setDisplayHomeAsUpEnabled(true); В onCreate()
Как задняя печать
Используйте finish() в действии для возврата в случае события click.
android:launchMode=»singleTop» в мой манифест и добавив android:launchMode=»singleTop» к активности сделал трюк для меня.
Это специально решило мою проблему, потому что я не хотел, чтобы Android создавал новый экземпляр предыдущего действия после нажатия кнопки « Up на панели инструментов – вместо этого я хотел использовать существующий экземпляр предыдущей операции, когда я поднялся по иерархии навигации.
Источник
Android studio get parent activity
The default value of this attribute is false . android:allowTaskReparenting Whether or not the activity can move from the task that started it to the task it has an affinity for when that task is next brought to the front — » true » if it can move, and » false » if it must remain with the task where it started.
If this attribute is not set, the value set by the corresponding allowTaskReparenting attribute of the element applies to the activity. The default value is » false «.
Normally when an activity is started, it’s associated with the task of the activity that started it and it stays there for its entire lifetime. You can use this attribute to force it to be re-parented to the task it has an affinity for when its current task is no longer displayed. Typically, it’s used to cause the activities of an application to move to the main task associated with that application.
For example, if an e-mail message contains a link to a web page, clicking the link brings up an activity that can display the page. That activity is defined by the browser application, but is launched as part of the e-mail task. If it’s reparented to the browser task, it will be shown when the browser next comes to the front, and will be absent when the e-mail task again comes forward.
The affinity of an activity is defined by the taskAffinity attribute. The affinity of a task is determined by reading the affinity of its root activity. Therefore, by definition, a root activity is always in a task with the same affinity. Since activities with » singleTask » or » singleInstance » launch modes can only be at the root of a task, re-parenting is limited to the » standard » and » singleTop » modes. (See also the launchMode attribute.)
android:alwaysRetainTaskState Whether or not the state of the task that the activity is in will always be maintained by the system — » true » if it will be, and » false » if the system is allowed to reset the task to its initial state in certain situations. The default value is » false «. This attribute is meaningful only for the root activity of a task; it’s ignored for all other activities.
Normally, the system clears a task (removes all activities from the stack above the root activity) in certain situations when the user re-selects that task from the home screen. Typically, this is done if the user hasn’t visited the task for a certain amount of time, such as 30 minutes.
However, when this attribute is » true «, users will always return to the task in its last state, regardless of how they get there. This is useful, for example, in an application like the web browser where there is a lot of state (such as multiple open tabs) that users would not like to lose.
android:autoRemoveFromRecents Whether or not tasks launched by activities with this attribute remains in the overview screen until the last activity in the task is completed. If true , the task is automatically removed from the overview screen. This overrides the caller’s use of FLAG_ACTIVITY_RETAIN_IN_RECENTS . It must be a boolean value, either » true » or » false «. android:banner A drawable resource providing an extended graphical banner for its associated item. Use with the tag to supply a default banner for a specific activity, or with the tag to supply a banner for all application activities.
The system uses the banner to represent an app in the Android TV home screen. Since the banner is displayed only in the home screen, it should only be specified by applications with an activity that handles the CATEGORY_LEANBACK_LAUNCHER intent.
This attribute must be set as a reference to a drawable resource containing the image (for example «@drawable/banner» ). There is no default banner.
See Provide a home screen banner in Get Started with TV Apps for more information.
android:clearTaskOnLaunch Whether or not all activities will be removed from the task, except for the root activity, whenever it is re-launched from the home screen — » true » if the task is always stripped down to its root activity, and » false » if not. The default value is » false «. This attribute is meaningful only for activities that start a new task (the root activity); it’s ignored for all other activities in the task.
When the value is » true «, every time users start the task again, they are brought to its root activity regardless of what they were last doing in the task and regardless of whether they used the Back or Home button to leave it. When the value is » false «, the task may be cleared of activities in some situations (see the alwaysRetainTaskState attribute), but not always.
Suppose, for example, that someone launches activity P from the home screen, and from there goes to activity Q. The user next presses Home, and then returns to activity P. Normally, the user would see activity Q, since that is what they were last doing in P’s task. However, if P set this flag to » true «, all of the activities on top of it (Q in this case) would be removed when the user launched activity P from the home screen. So the user would see only P when returning to the task.
If this attribute and allowTaskReparenting are both » true «, any activities that can be re-parented are moved to the task they share an affinity with; the remaining activities are then dropped, as described above.
This attribute is ignored if FLAG_ACTIVITY_RESET_TASK_IF_NEEDED is not set.
Requests the activity to be displayed in wide color gamut mode on compatible devices. In wide color gamut mode, a window can render outside of the SRGB gamut to display more vibrant colors. If the device doesn’t support wide color gamut rendering, this attribute has no effect. For more information about rendering in wide color mode, see Enhancing Graphics with Wide Color Content.
android:configChanges Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.
Note: Using this attribute should be avoided and used only as a last resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.
Any or all of the following strings are valid values for this attribute. Multiple values are separated by ‘ | ‘ — for example, » locale|navigation|orientation «.
Value | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
» density « | The display density has changed — the user might have specified a different display scale, or a different display might now be active. Added in API level 24. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» fontScale « | The font scaling factor has changed — the user has selected a new global font size. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» keyboard « | The keyboard type has changed — for example, the user has plugged in an external keyboard. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» keyboardHidden « | The keyboard accessibility has changed — for example, the user has revealed the hardware keyboard. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» layoutDirection « | The layout direction has changed — for example, changing from left-to-right (LTR) to right-to-left (RTL). Added in API level 17. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» locale « | The locale has changed — the user has selected a new language that text should be displayed in. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» mcc « | The IMSI mobile country code (MCC) has changed — a SIM has been detected and updated the MCC. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» mnc « | The IMSI mobile network code (MNC) has changed — a SIM has been detected and updated the MNC. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» navigation « | The navigation type (trackball/dpad) has changed. (This should never normally happen.) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» orientation « | The screen orientation has changed — the user has rotated the device. Note: If your application targets Android 3.2 (API level 13) or higher, then you should also declare the «screenSize» and «screenLayout» configurations, because they might also change when a device switches between portrait and landscape orientations. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» screenLayout « | The screen layout has changed — a different display might now be active. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» screenSize « | The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. Added in API level 13. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» smallestScreenSize « | The physical screen size has changed. This represents a change in size regardless of orientation, so will only change when the actual physical screen size has changed such as switching to an external display. A change to this configuration corresponds to a change in the smallestWidth configuration. Added in API level 13. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» touchscreen « | The touchscreen has changed. (This should never normally happen.) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» uiMode « | The user interface mode has changed — the user has placed the device into a desk or car dock, or the night mode has changed. For more information about the different UI modes, see UiModeManager . Added in API level 8. All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change. Note: To handle all Multi-Window related configuration changes use both «screenLayout» and «smallestScreenSize» . Multi-Window is supported in Android 7.0 (API level 24) or higher. Whether or not the activity is direct-boot aware; that is, whether or not it can run before the user unlocks the device. Note: During Direct Boot, an activity in your application can only access the data that is stored in device protected storage. The default value is «false» . android:documentLaunchMode Specifies how a new instance of an activity should be added to a task each time it is launched. This attribute permits the user to have multiple documents from the same application appear in the overview screen. This attribute has four values which produce the following effects when the user opens a document with the application:
Note: For values other than » none » and » never » the activity must be defined with launchMode=»standard» . If this attribute is not specified, documentLaunchMode=»none» is used. android:enabled Whether or not the activity can be instantiated by the system — «true» if it can be, and » false » if not. The default value is » true «. android:excludeFromRecents Whether or not the task initiated by this activity should be excluded from the list of recently used applications, the overview screen. That is, when this activity is the root activity of a new task, this attribute determines whether the task should not appear in the list of recent apps. Set » true » if the task should be excluded from the list; set » false » if it should be included. The default value is » false «. android:exported This element sets whether the activity can be launched by components of other applications:
If an activity in your app includes intent filters, set this element to » true » to allow other apps to start it. For example, if the activity is the main activity of the app and includes the category » android.intent.category.LAUNCHER «. If this element is set to » false » and an app tries to start the activity, the system throws an ActivityNotFoundException . This attribute is not the only way to limit an activity’s exposure to other applications. Permissions can also be used to limit the external entities that can invoke the activity (see the permission attribute). android:finishOnTaskLaunch Whether or not an existing instance of the activity should be shut down (finished), except for the root activity, whenever the user again launches its task (chooses the task on the home screen) — » true » if it should be shut down, and » false » if not. The default value is » false «. If this attribute and allowTaskReparenting are both » true «, this attribute trumps the other. The affinity of the activity is ignored. The activity is not re-parented, but destroyed. This attribute is ignored if FLAG_ACTIVITY_RESET_TASK_IF_NEEDED isn’t set. android:hardwareAccelerated Whether or not hardware-accelerated rendering should be enabled for this Activity — » true » if it should be enabled, and » false » if not. The default value is » false «. Starting from Android 3.0, a hardware-accelerated OpenGL renderer is available to applications, to improve performance for many common 2D graphics operations. When the hardware-accelerated renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. This results in smoother animations, smoother scrolling, and improved responsiveness overall, even for applications that do not explicitly make use the framework’s OpenGL libraries. Because of the increased resources required to enable hardware acceleration, your app will consume more RAM. Note that not all of the OpenGL 2D operations are accelerated. If you enable the hardware-accelerated renderer, test your application to ensure that it can make use of the renderer without errors. android:icon An icon representing the activity. The icon is displayed to users when a representation of the activity is required on-screen. For example, icons for activities that initiate tasks are displayed in the launcher window. The icon is often accompanied by a label (see the android:label attribute). This attribute must be set as a reference to a drawable resource containing the image definition. If it is not set, the icon specified for the application as a whole is used instead (see the element’s icon attribute). android:immersive Sets the immersive mode setting for the current activity. If the android:immersive attribute is set to true in the app’s manifest entry for this activity, the ActivityInfo.flags member always has its FLAG_IMMERSIVE bit set, even if the immersive mode is changed at runtime using the setImmersive() method. android:label A user-readable label for the activity. The label is displayed on-screen when the activity must be represented to the user. It’s often displayed along with the activity icon. If this attribute is not set, the label set for the application as a whole is used instead (see the element’s label attribute). The label should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. However, as a convenience while you’re developing the application, it can also be set as a raw string. android:launchMode An instruction on how the activity should be launched. There are four modes that work in conjunction with activity flags ( FLAG_ACTIVITY_* constants) in Intent objects to determine what should happen when the activity is called upon to handle an intent. They are: » standard » The default mode is » standard «. As shown in the table below, the modes fall into two main groups, with » standard » and » singleTop » activities on one side, and » singleTask » and » singleInstance » activities on the other. An activity with the » standard » or » singleTop » launch mode can be instantiated multiple times. The instances can belong to any task and can be located anywhere in the activity stack. Typically, they’re launched into the task that called startActivity() (unless the Intent object contains a FLAG_ACTIVITY_NEW_TASK instruction, in which case a different task is chosen — see the taskAffinity attribute). In contrast, » singleTask » and » singleInstance » activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task. The » standard » and » singleTop » modes differ from each other in just one respect: Every time there’s a new intent for a » standard » activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a » singleTop » activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the » singleTop » activity is in the target task, but not at the top of the stack, or if it’s at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack. Similarly, if you navigate up to an activity on the current stack, the behavior is determined by the parent activity’s launch mode. If the parent activity has launch mode singleTop (or the up intent contains FLAG_ACTIVITY_CLEAR_TOP ), the parent is brought to the top of the stack, and its state is preserved. The navigation intent is received by the parent activity’s onNewIntent() method. If the parent activity has launch mode standard (and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP ), the current activity and its parent are both popped off the stack, and a new instance of the parent activity is created to receive the navigation intent. The » singleTask » and » singleInstance » modes also differ from each other in only one respect: A » singleTask » activity allows other activities to be part of its task. It’s always at the root of its task, but other activities (necessarily » standard » and » singleTop » activities) can be launched into that task. A » singleInstance » activity, on the other hand, permits no other activities to be part of its task. It’s the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.
As shown in the table above, standard is the default mode and is appropriate for most types of activities. SingleTop is also a common and useful launch mode for many types of activities. The other modes — singleTask and singleInstance — are not appropriate for most applications , since they result in an interaction model that is likely to be unfamiliar to users and is very different from most other applications. Regardless of the launch mode that you choose, make sure to test the usability of the activity during launch and when navigating back to it from other activities and tasks using the Back button. For more information on launch modes and their interaction with Intent flags, see the Tasks and Back Stack document. android:lockTaskMode Determines how the system presents this activity when the device is running in lock task mode. Android can run tasks in an immersive, kiosk-like fashion called lock task mode. When the system runs in lock task mode, device users typically can’t see notifications, access non-allowlisted apps, or return to the home screen (unless the Home app is allowlisted). Only apps that have been allowlisted by a device policy controller (DPC) can run when the system is in lock task mode. System and privileged apps, however, can run in lock task mode without being allowlisted. The value can be any one of the following R.attr.lockTaskMode string values:
|