Broadcastreceiver, one of the four Android Components

Source: Internet
Author: User

I. broadcastreceiver: used to receive broadcasts,

It has a callback method: void
Onreceive (context curcontext, intent broadcastmsg) is used to process the received broadcast.

Broadcast receiving: you can create a new class for receiving and inherit from broadcastreceiver. You can also create a broadcastreceiver instance, and then write the onreceive method to implement it as follows:


Protected broadcastreceiver mevtreceiver = new broadcastreceiver (){
@ Override
Public void onreceive (Context
Context, intent ){
String action = intent. getaction ();

// Judge by the registered action to process the Broadcast
If (action. Equals ("android. Intent. Action. boot_completed ")){
// Do something
}
}
};

Ii. Use of broadcastreceiver (two registration methods are available before use)

Method 1: manual registration and manual Cancellation

Registration:

Intentfilter filter = new intentfilter ();

Filter. addaction ("android. provider. telephony. sms_mongod ");

Registerreceiver (mevtreceiver, filter );

// Mevtreceiver indicates the broadcast name and filter indicates the broadcast action.

Logout: At last, the broadcast should be canceled in the ondestroy program. The implementation is as follows:
@ Override
Public void ondestroy (){
Super. ondestroy ();
Unregisterreceiver (mplayerevtreceiver );
}

 

Method 2: Register in manifast. xml

<Explorer Android: Name = ". mevtreceiver">

<Intent-filter>
<Action Android: Name = "android. Intent. Action. boot_completed"/>
</Intent-filter>
</Cycler>

 

3. You can also send broadcasts by yourself.

Intent intent = new intent ("android. Intent. Action. boot_completed ");

Sendbroadcast (I );

Then you receive the broadcast and read the first line.

 

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.