Android Summary-Broadcastreceiver

Source: Internet
Author: User

Overview

The Broadcastreceiver will receive the intent sent by Sendbroadcast ().

If you do not need to send broadcasts across processes, consider using Localbroadcastmanager, which helps you register and send broadcasts in your own process, which is not cross-process, is more efficient, and does not need to consider the security issues that other applications bring.

There are two ways of registering receiver:
1. Dynamic registration, through Context.registerreceiver () to register the instance.
2. Static registration, by adding tags in the androidmanifest.xml to publish.

Note: If receiver is registered with Activity.onresume (), it should be unregister in Activity.onpause (). Do not unregister in activity.onsaveinstancestate () because the callback function is not called when the Activity is moved to the history stack.

Example
Dynamic registration:

    @Override    protectedvoidonResume() {        super.onResume();        // onResume 中注册Receiver        new IntentFilter(ACTION_RECEIVER_DYNAMIC);        registerReceiver(mReceiver, intentFilter);    }    @Override    protectedvoidonPause() {        super.onPause();        // onPause中取消Receiver        unregisterReceiver(mReceiver);    }

Static registration:

        <receiver android:name=". App. Broadcastreceiver1$customerreceiver1 "android:exported=" false ">                            <intent-filter android:priority="1">                <action android:name="Com.example.android.action.ACTION_RECEIVER_STATIC" />            </intent-filter>        </receiver>        <receiver android:name=". App. Broadcastreceiver1$customerreceiver3 "android:exported=" false "android:process= ": remote">                                                <intent-filterandroid:priority="2">                  <action android:name="Com.example.android.action.ACTION_RECEIVER_STATIC" />            </intent-filter>        </receiver>

There are two main types of broadcast that can be received:

    • Normal broadcast (sent via Context.sendbroadcast), asynchronous. All receivers that receive this broadcast will be executed in disorder, most of the time. This is more efficient, and also means that receivers cannot use execution results and some broken APIs.
    • Ordered broadcasts (sent via Context.sendorderedbroadcast) can only be delivered to one receiver at a time. Each receiver is executed sequentially, it passes the execution result to the next receiver, or completely interrupts the broadcast so it is no longer passed to the other receivers. The execution precedence of the receivers can be set by the intent-filter "android:priority" property, which is random if the precedence is the same.

Sendorderedbroadcast (Intent Intent,
String receiverpermission); Receiverpermission is null when the delegate does not require permission.

Even for ordinary broadcasts, the system may in some cases revert to only one receiver at a time. In particular, those receivers may need to create a process that can run only one receiver at a time to avoid overloading a new process with the system. But in any case, a disorderly receivers cannot return a result, nor can it terminate the broadcast.

Security

Broadcastreceiver can be used across processes, and some things need to be considered:

    • The intent namespace is global. Determine that the intent action name uses its own namespace, otherwise it may conflict with other apps.
    • When using Registerreceiver (Broadcastreceiver, Intentfilter), any application can send broadcasts to this receiver. Permissions can be used to control who can send broadcasts to this receiver.
    • When a broadcast is published via Manifest and "Intent-filters" is set, other apps can send it a broadcast, regardless of the filters you specify. To prevent other applications from sending broadcasts to it, you can set receiver's tag to "android:exported=" false "".
    • Other apps can also receive these broadcasts when you use Sendbroadcast (Intent) or related methods. You can specify who can receive by setting "Permissions". Starting with Ice_cream_sandwich, you can even assign to a single app by setting "Intent.setpackage".

There is no problem with Localbroadcastmanager, because both intent and broadcast are within the process.

Permissions can be implemented when sending and receiving broadcasts:

    • When sending, you can provide a non-empty parameter to Sendbroadcast (Intent, String) or Sendorderedbroadcast (Intent, String, Broadcastreceiver, Android.os.Handler, int, String, Bundle). This broadcast can only be received if the permission receivers is acquired.
    • At the time of receipt, a non-empty permission is provided when registering receiver. Either, call Registerreceiver (Broadcastreceiver, Intentfilter, String, Android.os.Handler) to pass a permission; Add permission to the Androidmanifest.xml tag. Only apps that have the appropriate permissions (used in Androidmanifest.xml to request) can send intent to receiver.

Before using permission, the first thing to declare in Androidmanifest.xml, such as:<permission android:name="android.permission.CUSTOMER_RECEIVER"/>

Receiver Lifecycle

Broadcastreceiver objects are only useful when calling OnReceive (Context, Intent), and once this method is executed, the system will have to destroy the object and never activate it.

There is an important impact in the implementation of OnReceive (Context, Intent): Asynchronous operations are not allowed because you need to receive the return result of an asynchronous operation, but this time broadcastreceiver is not in the running state then the system may kill its process before the asynchronous operation completes.
In particular, you can no longer display a dialog box in Broadcastreceiver or call the bind service. For the former, you can use the Notificationmanager API instead, and for the latter you can use Context.startservice () to send commands to the service.

The onreceive is executed in the main thread.

Process Lifecycle

When a process has broadcastreceiver in execution, the process is the foreground process and the system will keep it running, unless in some extreme cases.

As long as onreceive () is executed, the broadcastreceiver is not active, and the importance of its process depends on the other components in the process. This is especially important because the join process contains only broadcastreceiver, so when OnReceive () is executed, the system will assume that the process is empty, thus killing it for other more important processes.

Receiver Label
    <receiver 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>

Property:

    • android:enabled
      This property is used to define whether the system can instantiate the broadcast sink, and if set to true, it can be instantiated and, if set to false, cannot be instantiated. The default value is true.

    • android:exported
      Whether receiver can receive broadcasts from other applications. If set to true, the ability to receive, if set to false, is not acceptable.

    • Android:icon
      Receiver's icon. This property must be set with a drawing resource that contains a picture definition. If this property is not set, the Icon property value of the element is applied instead.

    • Android:label
      This property sets a user-readable text label to the broadcast receiver. If this property is not set, then the value of the element's label property is used instead.

    • Android:name
      This property value is set by the class name of the implementation class of the broadcast receiver, which is a subclass of the Broadcastreceiver class. You typically use the full name of the class to set (for example: Com.example.project.ReportReceiver). However, you can also use shorthand (for example:. Reportreceiver). The package name set by the Packages property in the element is automatically added to the abbreviated name.

Once the application has been published, the name should not be changed (unless android:exported= "false").

    • android:permission
      This property is used to define the permissions that are necessary to send a message to the broadcaster of the broadcast receiver. If this property is not set, then the permissions set by the element's permission property apply to this broadcast sink. If the element also does not have permissions set, the sink is not protected by permissions.

    • android:process
      This property is used to set the broadcast sink that should run in that process. Typically, all components of an application run in the default process created for the application, and it has the same name as the application package name. The process property of an element can set a different default process for all its components, but each of its components has its own process property that overrides this default setting, allowing one application to be separated into multiple processes.
      If this property value starts with ":", the system creates a new, application-private process when needed, and the broadcast sink runs in the process. If the property value starts with a lowercase letter, the receiver runs in a global process named after the property value, which provides the permissions to make it work. This allows different application components to share the process.

Android Summary-Broadcastreceiver

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.