"Android" 15.2 broadcast

Source: Internet
Author: User

Category: C #, Android, VS2015;

Date Created: 2016-02-29 I. INTRODUCTION

Both the Android system and your own applications can send and receive broadcast messages through indent. Broadcast content can be either custom information or Android system information. For example, changes in the network connection, changes in battery power, changes in system settings, receipt of a new text message 、、...... such as

1. Send a broadcast message

Broadcast messages are generally sent forward through the background service. Of course, it is also possible to send broadcasts to other activity in an activity, but this is a rare situation.

To send a broadcast through a service, you first define a subclass that inherits from services, for example:

[Service]

public class Myservice:service

{

......

}

In the service subclass, override the Startcommandresult () method, and then create an intent instance in the method, and you can also call the Putextra () method of the intent instance to include the additional message to be sent (optional). Finally, call the Sendbroadcast () method to broadcast the message. For example:

Intent = new Intent (action);

Intent. PutExtra ("message", "This is from the broadcast");

Sendbroadcast (Intent);

Attention:

(a) When sending a broadcast with intent, you must specify the action to be performed by using "globally unique identifier" in the parameter, in short, just make sure that the action name is unique throughout the project.

In practical applications, action strings are typically represented by "solution name + project name + action name", for example:

public static readonly String action = "Mybroadcastdemo.action1";

You can also use a custom namespace + action name to represent it. For example:

public static readonly String action = "Www.cnblogs.com.rainmj.MyBroadcastDemo";

However, these are some of the agreed-upon practices that we feel are better than the ones that must be done. In other words, the only requirement is not to have the same action name in the same project, which is what the "globally unique identifier" means.

(b) Since the broadcast is generally done through background services, in order to not allow background services to affect the front-end interface operations, you can send through task or thread (see example). Of course, if the service takes a short time, such as sending only a simple string, there is no need to implement it with a task or thread.

The complete code for sending the broadcast is shown in the Ch1501Service.cs file in the example.

2. Receive broadcast messages

For the broadcast receiver, any application class registered with Broadcastreceiver can receive a broadcast message from a class that inherits from Broadcastreceiver, and the Broadcastreceiver subclass that implements the receiving broadcast is called a broadcast receiver.

Broadcast receivers (broadcast receivers) receive broadcast content typically from Android's built-in standard services, and can also come from services that you define yourself.

For example:

public class Mybroadcastreceiver:broadcastreceiver

{

......

}

Once the broadcast receiver is started, it will automatically listen to your registered broadcasts and receive broadcast messages in the OnReceive () method. Therefore, to receive broadcasts normally, you must override the OnReceive () method in that subclass, for example:

public override void OnReceive (context context, Intent Intent)

{

......

}

By default, Android requires that the OnReceive method must be executed within 5 seconds, or Android will consider the component unresponsive and prompt the user to forcibly close the component.

The complete code to receive the broadcast is shown in the Ch1501BroadcastReceiver.cs file in the example.

3. Registered and received broadcast address

It is generally registered in the activity to use which broadcast receiver to receive the broadcast.

There are two ways to register to receive broadcast addresses, one is implemented through C # code (common), and the other is implemented in configuration file Androidmanifest.xml (not commonly used).

Examples of approaches implemented through C # code are as follows:

var receiver = new Mybroadcastreceiver ();

Registerreceiver (receiver, new Intentfilter (myservice.action));

StartService (New Intent (This, typeof (MyService)));

This code registers a broadcastreceiver and specifies the action to be performed via the Intentfilter (Intent Filter), and can then invoke the StartService () method to start the broadcast service.

After calling Registerreceiver (), the system will automatically configure the intent filter in the configuration file (Androidmanifest.xml) without the need for us to manually configure it in this file. Second, example 1 run

This example shows how to periodically send multiple types of broadcasts. With this example, I believe you should be able to really understand the meaning of the "action" to be sent, and also understand how to register multiple actions in a receiver through the intent filter.

This example uses the features of the Android service that will be introduced in the next chapter.

Third, the main design steps

1. Add Ch1501_main.axml File

Add the file under the Resource/layout folder.

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent">    <ButtonAndroid:id= "@+id/ch1501_btnstart"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Start service (send broadcast)" />    <ButtonAndroid:id= "@+id/ch1501_btnstop"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Stop service (stop broadcasting)" />    <TextViewAndroid:text=""android:textappearance= "? Android:attr/textappearancesmall"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:id= "@+id/textview1"Android:layout_marginleft= "10DP"Android:layout_margintop= "50DP" /></LinearLayout>

2. Add Ch1501service File

Add the file under the Srcdemos folder, and the template selects "Class".

usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.runtime;usingSystem;usingSystem.Threading.Tasks;namespacemydemos.srcdemos{[Service] Public classCh1501service:service { Public Const stringAction1 ="Www.cnblogs.com.rainmj.ch1501Service";  Public Const stringAction2 ="MyDemos.ch1501Service.Info1";  Public Const stringAction3 ="MyDemos.ch1501Service.Info2";  Public Const stringAction4 ="MyDemos.ch1501Service.Info3";  Public Static BOOLIscancel; [return: Generatedenum] Public OverrideStartcommandresult Onstartcommand (Intent Intent, [generatedenum] startcommandflags flags,intStartid) {            //Generally, different broadcast information should be sent by action according to different situations .//If you send only one broadcast, you can send it directly like this, and you don't need to implement it with Task.run.//Intent = new Intent (action1); //Sendbroadcast (Intent); //if it is a long-running background service, in order not to affect the interface operation, it is best to use//threads to implement, such as the progress of sending background processing. //The following is an example of randomly selecting an action every 1 seconds to demonstrate a long running//service and the way to send different types of broadcasts to the front desk regularlyTask.run (Async() ={Random R=NewRandom (); string[] actions ={action1, Action2, Action3, action4}; stringAction = actions[0];  while(true)                {                    if(Iscancel = =true)                    {                         Break; } Intent=NewIntent (action);                    Sendbroadcast (Intent); Action=Actions[r.next (actions.                    Length)]; awaitTask.delay ( +);            }            }); returnStartcommandresult.sticky; }         Public Overrideibinder onbind (Intent Intent) {return NULL; }    }}

3. Add Ch1501BroadcastReceiver.cs File

Add the file under the Srcdemos folder, and the template selects "Class".

usingandroid.content;usingAndroid.widget;namespacemydemos.srcdemos{ Public classCh1501broadcastreceiver:broadcastreceiver {PrivateTextView txt;  PublicCh1501broadcastreceiver (ch1501mainactivity activity) {txt= activity. Findviewbyid<textview>(RESOURCE.ID.TEXTVIEW1); }         Public Override voidOnReceive (Context context, Intent Intent) {//the received intent should be docked here. Action is processed separately//for the sake of simplicity, the example only shows the string on the interface.Txt. Text + ="\ n Received:"+Intent.        Action; }    }}

4. Add Ch1501MainActivity.cs File

Add the file under the Srcdemos folder, and the template selects "Activity".

usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.widget;namespacemydemos.srcdemos{[Activity (Label="basic usage of "example 15-1" broadcast")]     Public classch1501mainactivity:activity {Privatech1501broadcastreceiver Receiver; PrivateIntent Intent; protected Override voidOnCreate (Bundle savedinstancestate) {Base.            OnCreate (savedinstancestate);            Setcontentview (Resource.Layout.ch1501_Main); varTXT = findviewbyid<textview>(RESOURCE.ID.TEXTVIEW1); Intentfilter Intentfilter=NewIntentfilter ();            Intentfilter.addaction (Ch1501service.action1);            Intentfilter.addaction (Ch1501service.action2);            Intentfilter.addaction (Ch1501service.action3);            Intentfilter.addaction (CH1501SERVICE.ACTION4); Receiver=NewCh1501broadcastreceiver ( This);            Registerreceiver (receiver, intentfilter); Intent=NewIntent ( This,typeof(Ch1501service)); varbtnstart = findviewbyid<button>(Resource.Id.ch1501_btnStart); Btnstart.click+=Delegate{txt. Text=""; Ch1501service.iscancel=false;            StartService (Intent);            }; varBtnstop = findviewbyid<button>(Resource.Id.ch1501_btnStop); Btnstop.click+=Delegate{Ch1501service.iscancel=true;            StopService (Intent);        }; }        protected Override voidOnDestroy () {unregisterreceiver (receiver); Ch1501service.iscancel=true;            StopService (Intent); Base.        OnDestroy (); }    }}

"Android" 15.2 broadcast

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.