A simple example of Android broadcast Receiver

Source: Internet
Author: User
Android broadcastreceiver

(Learning the video from instructor Mars)

Registration Method

There are two types:

One is declared in androidmanifest. xml:

<Cycler
Android: Name =". Test_receiver"
>

<Intent-filter>

<Action
Android: Name ="Android. Intent. Action. Sss"
/>

</Intent-filter>

</Cycler>

Code in the class file:

Intent intent =
NewIntent ();

Intent. setaction ("android. Intent. Action. Sss ");

Test_bcactivity.This. Sendbroadcast (intent );

 

The other is code registration:

Bind a consumer

PublicstaticfinalString
Sms_received_action=
"Android. provider. telephony. sms_received ";

// Generate a receiver object

Extends ER =
NewTest_receiver ();

//
Generate a filter object

Intentfilter =
NewIntentfilter ();

//
Add an action for the filter

Intentfilter. addaction (Sms_received_action);

Test_bcactivity.This. Registerreceiver (receiver, intentfilter );

Unbind a consumer

Test_bcactivity.This. Unregisterreceiver (receiver );

The main difference between the two is that the broadcast mechanism registered in the XML file still runs after the application is closed. Always run. The broadcast registered by code is closed after the application is closed and takes effect immediately.

 

Code for the Cycler class

PublicclassTest_receiver
ExtendsBroadcastreceiver {

PublicTest_receiver (){

Log.D("Test_receiver ",
"Constructor ");

}

@ Override

PublicvoidOnreceive (context, intent ){

//
TodoAuto-generated method stub

Log.D("Test_receiver ",
"Onreceive ");

}

}

 

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.