Android broadcastreceiver Learning

Source: Internet
Author: User

BroadcastreceiverUsed to receive broadcast intent asynchronously. There are two main categories for receiving broadcasts:

  • Normal BroadcastNormal broadcasts (UseContext.sendBroadcast() Sending) is completely asynchronous. They all run in an undefined order, usually at the same time. This will be more effective, but it means that the consumer cannot contain the results to be used or the APIs to be aborted.
  • Ordered BroadcastOrdered broadcasts (UseContext.sendOrderedBroadcast()Sent) each time it is sent to a receiver. The so-called order means that each worker can be propagated to the next worker after execution, or the propagation can be completely aborted without being propagated to other worker workers. The sequence of worker er running can be controlled by Android: priority in matched intent-filter. When priority has the same priority, worker er runs in any order.
Note that, even in normal broadcasts, the system may resume one transmission to a receiver in some cases. In particular, a worker er may need to create a process. To avoid system overload, only one worker er can be run at a time. Broadcast receiver does not provide a visual interface for displaying broadcast information. Notification and notification manager can be used to display the broadcast information content, icons, and vibration information. LifecycleA broadcastreceiver object is valid only when onreceive (context, intent) is called. After the function is returned, this object is invalid and the lifecycle ends. Therefore, we can see from this feature that the onreceive (context, intent) function called cannot have too many time-consuming operations and cannot be executed using threads. For time-consuming operations, start service. Because broadcastreceiver may be invalid when other asynchronous operations return results. Send BroadcastIt is relatively simple to broadcast events. To build intent objects, you can call the sendbroadcast (intent) method to send broadcasts. In addition, there are sendorderedbroadcast (), sendstickybroadcast () and other methods. Please refer to the API Doc. 1. new intent with action name intent = new intent (string action); or just new intent, then intent. setaction (string action); 2.set data, etc., after preparation, in activity, sendbroadcast (intent); // send Broadcast Receive BroadcastIt is implemented by defining an inherited broadcastreceiver class, inheriting this class, overwriting its onreceiver method, and responding to events in this method. Public class smsreceiver
Extends broadcastreceiver {

@ Override
Public void
Onreceive (context, intent ){
// Get data from SMS intent
Bundle bundle = intent. getextras ();
If (bundle! =
Null ){
// Get message by "PDUS"

Object [] objarray = (object []) bundle. Get ("PDUS ");

// Rebuild SMS
Smsmessage [] messages = new smsmessage [objarray. Length];

For (INT I = 0; I <objarray. length; I ++ ){

Messages [I] = smsmessage. createfrompdu (byte []) objarray [I]);

Stringbuilder STR = new stringbuilder ("from :");

Str. append (messages [I]. getdisplayoriginatingaddress ());

Str. append ("\ nmessage: \ n ");

Str. append (messages [I]. getdisplaymessagebody ());

Toast. maketext (context, str. tostring (), Toast. length_long)

. Show ();
}
}
}
}

Register aggregerThere are two registration methods:
1. static mode: Define the receiver in the application of androidmanifest. xml and set the action to be received. <Cycler
Android: Name = ". smsreceiver">

<Intent-filter>

<Action
Android: Name = "android. provider. telephony. sms_received"
/>
</Intent-filter>

</Cycler> 2. In the dynamic mode, call a function in the activity to register it, which is similar to static content. One parameter is the receiver, and the other is the intentfilter, which contains the action to be received. Public class hellodemo
Extends activity {
Private broadcastreceiver extends er;

@ Override
Protected
Void onstart (){
Super. onstart ();

Extends ER = new callpolicer ();

Registerreceiver (explorer, new intentfilter ("android. Intent. Action. phone_state "));

}

@ Override
Protected
Void onstop (){
Unregisterreceiver (receiver );
Super. onstop ();
}
} A single receiver can receive multiple actions, that is, there can be multiple intent-filters, which need to be determined by intent. getaction (action name) in onreceive.
I personally recommend that you use the static registration method. The system manages the handler, and all the schedulers in the program can be clearly viewed in XML. The dynamic registration method is hidden in the code, which is hard to find.
In addition, you must note that you must call the context. unregisterreceiver () method before exiting the program. Generally, registration is performed in onstart () of the activity, and cancellation is performed in onstop. Official reminder: If you have registered in activity. onresume (), you must log out of activity. onpause.Permission permission
To receive certain actions, you must add the corresponding permission in androidmanifest. xml. For example, to receive SMS: <uses-Permission
Android: Name = "android. Permission. receive_sms"
/>

The following code is provided for dynamically registered callcycler for receiving incoming calls. One way is to directly read intent. getstringextra ("incoming_number") to obtain the incoming call number: public class callcycler.
Extends broadcastreceiver {

@ Override
Public void onreceive (context, intent ){

Telephonymanager telemanager = (telephonymanager) Context. getsystemservice (context. telephony_service );


Switch (telemanager. getcallstate ()){

Case telephonymanager. call_state_ringing:
// Ring the bell
Toast. maketext (context, "ringing:" + intent. getstringextra ("incoming_number"), Toast. length_long). Show ();

Break;
Case telephonymanager. call_state_offhook:
// Answer
Toast. maketext (context, "offhook:" + intent. getstringextra ("incoming_number"), Toast. length_long). Show ();

Break;
Case telephonymanager. call_state_idle:
// Hang up
Toast. maketext (m_context, "Idle:" + incomingnumber, Toast. length_long). Show ();

Break;
}
}
}

During operation, it is found that the incoming call number can be obtained only when the bell rings, and neither the answer nor the end of the call can be obtained successfully, and the display is null.

The other method is to monitor the status change through the oncallstatechanged of the phonestatelistener: public class callpolicer
Extends broadcastreceiver {

Private context m_context;
@ Override
Public void onreceive (context, intent ){

M_context = context;
Telephonymanager telemanager = (telephonymanager) Context. getsystemservice (context. telephony_service );

Telemanager. Listen (New phonestatelistener (){

@ Override
Public
Void oncallstatechanged (INT state, string incomingnumber ){

Switch (state ){

Case telephonymanager. call_state_ringing:
// Ring the bell
Toast. maketext (m_context,
"Ringing:" + incomingnumber, Toast. length_long)
. Show ();
Break;

Case telephonymanager. call_state_offhook:
// Answer
Toast. maketext (m_context,
"Offhook:" + incomingnumber, Toast. length_long)
. Show ();
Break;

Case telephonymanager. call_state_idle:
// Hang up
Toast. maketext (m_context,
"Idle:" + incomingnumber, Toast. length_long)
. Show ();
Break;

}
}, Phonestatelistener. listen_call_state );
}
}

During running, it is also found that the incomingnumber is obtained as blank when it is answered and hung up. Because the listener changes the call status, the caller will be called three times. You must add the following permissions to listen to the call status: <uses-Permission
Android: Name = "android. Permission. read_phone_state"/>

============ Conclusion: 1. For the intent object of sendbroadcast, you need to set its action name;
2. It is recommended to explicitly specify the consumer in the configuration file androidmanifest. xml;
3. one worker can receive multiple actions. 4. each time a broadcast is received, a new broadcast receiving object is generated, and onreceive is called again; 5. do not handle too many logic problems in broadcast. It is recommended that complicated logic be handled by activity or service.

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.