- синтаксис:
<receiver android:directBootAware=["true" | "false"] android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:label="string resource" android:name="string" android:permission="string" android:process="string" > ... </receiver>
- содержится в:
-
<application>
- может содержать:
-
<intent-filter>
<meta-data>
- описание:
- Объявляет широковещательный приемник, подкласс
BroadcastReceiver
, как один из компонентов приложения. Приемники широковещательной рассылки позволяют приложениям получать намерения, транслируемые системой или другими приложениями, даже если другие компоненты приложения не работают.Есть два способа сделать приемник широковещательного вещания известным системе. Один из них — объявить это в файле манифеста с помощью этого элемента. Другой способ — динамически создать получатель в коде и зарегистрировать его с помощью метода
Context.registerReceiver()
или одной из его перегруженных версий.Дополнительные сведения о том, как динамически создавать получатели, см. в описании класса
BroadcastReceiver
.Если этот приемник обрабатывает несистемные широковещательные сообщения, укажите значение для
android:exported
. Установите для этого значения значение"true"
если вы хотите, чтобы ваш приемник мог принимать трансляции из других приложений, или"false"
если вы хотите, чтобы ваш приемник мог принимать трансляции только из вашего собственного приложения.Вам не нужно удалять атрибут
android:permission
если вы его уже объявили.Предупреждение: ограничьте количество приемников вещания, которые вы устанавливаете в своем приложении. Слишком большое количество приемников вещания может повлиять на производительность вашего приложения и время автономной работы устройств пользователей. Дополнительные сведения об API, которые можно использовать вместо класса
BroadcastReceiver
для планирования фоновой работы, см. в разделе Фоновая оптимизация . - атрибуты:
-
android:directBootAware
Поддерживает ли приемник вещания Direct-Boot , то есть может ли он работать до того, как пользователь разблокирует устройство.
Примечание. Во время прямой загрузки приемник вещания в вашем приложении может получить доступ только к данным, хранящимся в защищенном хранилище устройства .
Значение по умолчанию —
"false"
.-
android:enabled
- Может ли система создать экземпляр широковещательного приемника. Это
"true"
если это возможно, и"false"
если нет. Значение по умолчанию —"true"
.Элемент
<application>
имеет собственный атрибутenabled
, который применяется ко всем компонентам приложения, включая приемники широковещательных сообщений. Чтобы включить широковещательный приемник, атрибуты<application>
и<receiver>
должны иметь значение"true"
. Если какой-либо из них имеет значение"false"
, он отключен и не может быть создан. -
android:exported
- Может ли приемник вещания получать сообщения из несистемных источников за пределами своего приложения. Это
"true"
если возможно, и"false"
если нет. Если установлено"false"
, получатель широковещательной рассылки получает только те сообщения, которые отправлены системой, компонентами того же приложения или приложениями с тем же идентификатором пользователя.Если не указано, значение по умолчанию зависит от того, содержит ли приемник широковещательной передачи фильтры намерений. Если получатель содержит хотя бы один фильтр намерений, значение по умолчанию —
"true"
. В противном случае значение по умолчанию —"false"
.Этот атрибут — не единственный способ ограничить внешнее воздействие приемника вещания. Вы также можете использовать разрешение, чтобы ограничить внешние объекты, которые могут отправлять ему сообщения. См. атрибут
permission
. -
android:icon
- Значок, обозначающий приемник вещания. Этот атрибут устанавливается как ссылка на ресурс, который можно рисовать, содержащий определение изображения. Если он не установлен, вместо него используется значок, указанный для приложения в целом. См. атрибут
icon
элемента<application>
.Значок получателя широковещательной передачи, заданный здесь или элементом
<application>
, также является значком по умолчанию для всех фильтров намерений получателя. См. атрибутicon
элемента<intent-filter>
. -
android:label
- Читаемая пользователем этикетка приемника вещания. Если этот атрибут не установлен, вместо него используется метка, установленная для приложения в целом. См. атрибут
label
элемента<application>
.Метка получателя широковещательной передачи, заданная здесь или элементом
<application>
, также является меткой по умолчанию для всех фильтров намерений получателя. См. атрибутlabel
элемента<intent-filter>
.Метка задается как ссылка на строковый ресурс, поэтому ее можно локализовать, как и другие строки в пользовательском интерфейсе. Однако для удобства при разработке приложения его также можно задать как необработанную строку.
-
android:name
- Имя класса, реализующего широковещательный приемник, подкласса
BroadcastReceiver
. Это полное имя класса, например"com.example.project.ReportReceiver"
. Однако в качестве сокращения, если первым символом имени является точка, например".ReportReceiver"
, она добавляется к имени пакета, указанному в элементе<manifest>
.После публикации приложения не меняйте это имя , если только вы не установили
android:exported ="false"
.По умолчанию нет. Имя должно быть указано.
-
android:permission
- Имя разрешения, которое необходимо вещателям для отправки сообщения получателю вещания. Если этот атрибут не установлен, разрешение, установленное атрибутом
permission
элемента<application>
, применяется к получателю широковещательной передачи. Если ни один из атрибутов не установлен, получатель не защищен разрешением.Дополнительные сведения о разрешениях см. в разделе «Разрешения» обзора манифеста приложения и в советах по безопасности .
-
android:process
- Имя процесса, в котором работает приемник широковещательных сообщений. Обычно все компоненты приложения выполняются в процессе по умолчанию, созданном для приложения. Он имеет то же имя, что и пакет приложения.
Атрибут
process
элемента<application>
может устанавливать разные значения по умолчанию для всех компонентов. Но каждый компонент может переопределить значение по умолчанию, используя свой собственный атрибутprocess
, что позволяет распределить приложение по нескольким процессам.Если имя, присвоенное этому атрибуту, начинается с двоеточия (
:
), при необходимости создается новый процесс, частный для приложения, и приемник широковещательной рассылки запускается в этом процессе.Если имя процесса начинается с символа нижнего регистра, получатель запускается в глобальном процессе с таким именем, при условии, что у него есть на это разрешение. Это позволяет компонентам разных приложений совместно использовать процесс, сокращая использование ресурсов.
-
- представлено в:
- API уровня 1
<получатель>
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-29 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-07-29 UTC."],[],[],null,["# <receiver\u003e\n\nsyntax:\n:\n\n ```xml\n \u003creceiver android:directBootAware=[\"true\" | \"false\"]\n android:enabled=[\"true\" | \"false\"]\n android:exported=[\"true\" | \"false\"]\n android:icon=\"drawable resource\"\n android:label=\"string resource\"\n android:name=\"string\"\n android:permission=\"string\"\n android:process=\"string\" \u003e\n ...\n \u003c/receiver\u003e\n ```\n\ncontained in:\n: [\u003capplication\u003e](/guide/topics/manifest/application-element)\n\ncan contain:\n: [\u003cintent-filter\u003e](/guide/topics/manifest/intent-filter-element)\n\n [\u003cmeta-data\u003e](/guide/topics/manifest/meta-data-element)\n\ndescription:\n: Declares a broadcast receiver, a [BroadcastReceiver](/reference/android/content/BroadcastReceiver)\n subclass, as one of the application's components. Broadcast receivers enable\n applications to receive intents that are broadcast by the system or by other\n applications, even when other components of the application aren't running.\n\n\n There are two ways to make a broadcast receiver known to the system. One is to\n declare it in the manifest file with this element. The other is to create\n the receiver dynamically in code and register it with the\n [Context.registerReceiver()](/reference/android/content/Context#registerReceiver(android.content.BroadcastReceiver,%20android.content.IntentFilter))\n method or one of its overloaded versions.\n\n\n For more information about how to dynamically create receivers, see the\n [BroadcastReceiver](/reference/android/content/BroadcastReceiver) class\n description.\n\n\n If this receiver handles non-system broadcasts, specify a value for `android:exported`.\n Set this value to `\"true\"` if you want your receiver to be able to\n receiver broadcasts from other applications or `\"false\"` if you only\n want your receiver to be able to receive broadcasts from your own app.\n\n\n You don't have to remove the `android:permission` attribute if you\n already declared it.\n\n\n **Warning:** Limit how many broadcast\n receivers you set in your app. Having too many broadcast receivers can\n affect your app's performance and the battery life of users' devices.\n For more information about APIs you can use instead of the\n `BroadcastReceiver` class for scheduling background work, see\n [Background optimization](/topic/performance/background-optimization).\n\nattributes:\n:\n\n `android:directBootAware`\n\n : Whether the broadcast receiver is *Direct-Boot aware*, that\n is, whether it can run before the user unlocks the device.\n\n **Note:** During\n [Direct Boot](/training/articles/direct-boot), a broadcast\n receiver in your application can only access the data that is stored in\n *device protected* storage.\n\n The default value is `\"false\"`.\n\n `android:enabled`\n : Whether the broadcast receiver can be instantiated by the system. It's\n `\"true\"` if it can be, and `\"false\"` if not. The default value\n is `\"true\"`.\n\n\n The [\u003capplication\u003e](/guide/topics/manifest/application-element) element has its own\n [enabled](/guide/topics/manifest/application-element#enabled) attribute that applies to all\n application components, including broadcast receivers. The\n `\u003capplication\u003e` and\n `\u003creceiver\u003e` attributes must both be `\"true\"` for\n the broadcast receiver to be enabled. If either is `\"false\"`, it's\n disabled and can't be instantiated.\n\n `android:exported`\n : Whether the broadcast receiver can receive messages from non-system sources\n outside its application. It's `\"true\"` if it can, and `\"false\"`\n if not. If `\"false\"`, the only messages the broadcast receiver\n receives are those sent by the system, components of the same application, or applications\n with the same user ID.\n\n\n If unspecified, the default value depends on whether the broadcast receiver contains intent\n filters. If the receiver contains at least one intent filter, then the default value is\n `\"true\"`. Otherwise, the default value is `\"false\"`.\n\n\n This attribute is not the only way to limit a broadcast receiver's external exposure.\n You can also use a permission to limit the external entities that can send it messages.\n See the [permission](/guide/topics/manifest/receiver-element#prmsn) attribute.\n\n `android:icon`\n : An icon representing the broadcast receiver. This attribute is set\n as a reference to a drawable resource containing the image definition.\n If it isn't set, the icon specified for the application as a whole is used\n instead. See the [\u003capplication\u003e](/guide/topics/manifest/application-element)\n element's [icon](/guide/topics/manifest/application-element#icon) attribute.\n\n\n The broadcast receiver's icon, whether set here or by the\n `\u003capplication\u003e` element, is also the\n default icon for all the receiver's intent filters. See the\n [\u003cintent-filter\u003e](/guide/topics/manifest/intent-filter-element) element's\n [icon](/guide/topics/manifest/intent-filter-element#icon) attribute.\n\n `android:label`\n : A user-readable label for the broadcast receiver. If this attribute isn't\n set, the label set for the application as a whole is\n used instead. See the [\u003capplication\u003e](/guide/topics/manifest/application-element) element's\n [label](/guide/topics/manifest/application-element#label) attribute.\n\n\n The broadcast receiver's label, whether set here or by the\n `\u003capplication\u003e` element, is also the\n default label for all the receiver's intent filters. See the\n [\u003cintent-filter\u003e](/guide/topics/manifest/intent-filter-element) element's\n [label](/guide/topics/manifest/intent-filter-element#label) attribute.\n\n\n The label is set as a reference to a string resource, so that\n it can be localized like other strings in the user interface.\n However, as a convenience while you're developing the application,\n it can also be set as a raw string.\n\n `android:name`\n : The name of the class that implements the broadcast receiver, a subclass of\n [BroadcastReceiver](/reference/android/content/BroadcastReceiver). This is a fully qualified\n class name, such as `\"com.example.project.ReportReceiver\"`. However,\n as a shorthand, if the first character of the name is a period, for example,\n `\".ReportReceiver\"`, it is appended to the package name specified in\n the [\u003cmanifest\u003e](/guide/topics/manifest/manifest-element) element.\n\n Once you publish your application, [don't\n change this name](http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html), unless you set [android:exported](#exported)`=\"false\"`.\n\n\n There is no default. The name must be specified.\n\n `android:permission`\n : The name of a permission that broadcasters need in order to send a\n message to the broadcast receiver.\n If this attribute isn't set, the permission set by the\n [\u003capplication\u003e](/guide/topics/manifest/application-element) element's\n [permission](/guide/topics/manifest/application-element#prmsn) attribute applies\n to the broadcast receiver. If neither attribute is set, the receiver\n isn't protected by a permission.\n\n\n For more information about permissions, see the\n [Permissions](/guide/topics/manifest/manifest-intro#perms)\n section in the app manifest overview and\n [Security tips](/guide/topics/security/security).\n\n `android:process`\n\n : The name of the process in which the broadcast receiver runs. Normally, all components of an application run in the default process created for the application. It has the same name as the application package.\u003cbr /\u003e\n\n The\n [\u003capplication\u003e](/guide/topics/manifest/application-element) element's\n [process](/guide/topics/manifest/application-element#proc) attribute can set a different\n default for all components. But each component can override the default\n with its own `process` attribute, letting you spread your\n application across multiple processes.\n\n\n If the name assigned to this attribute begins with a colon (`:`), a new\n process, private to the application, is created when it's needed, and\n the broadcast receiver runs in that process.\n\n\n If the process name begins with a lowercase character, the receiver runs\n in a global process of that name, provided that it has permission to do so.\n This lets components in different applications share a process, reducing\n resource usage.\n\nintroduced in:\n: API level 1"]]