Android development path 02 (talking about BroadcastReceiver) and broadcastreceiver

Source: Internet
Author: User

Android development path 02 (talking about BroadcastReceiver) and broadcastreceiver

I. BroadcastReceiver is used to receive broadcasts from systems and applications. The application is as follows:

1. After the boot is complete, the system will generate a broadcast -----> receive this broadcast to enable the startup service function;

2. When the network status changes, the system generates a broadcast. After receiving the broadcast, the system can promptly prompt and save data;

When the battery power changes, the system generates a broadcast. When the battery power is low, the system notifies the user of the timely saving progress;

The Broadcast Mechanism in Android is well designed, greatly reducing the development workload and development cycle.

2. Static registration of broadcast recipients and Dynamic Registration of broadcast recipients

① Create a BroadcastReceiver object to inherit from the android. content. BroadcastReceiver class and implement its onReceive method.

Example: public class MyReceiver extends BroadcastReceiver {

 

@ Override

Public void onReceive (Context context, Intent intent ){

// Obtain the data in the broadcast Intent.

String msg = intent. getStringExtra ("msg ");

// Output prompt information on the Interface

Toast. makeText (context, msg, Toast. LENGTH_LONG). show ();

}

 

}

After we have created our BroadcastReceiver, we do not need to register a specified broadcast address for it.

② Register static registration of broadcast addresses for BroadcastReceiver: static registration is configured in the AndroidManifest. xml file, for example:

<Cycler android: name = ". mycycler">

<Intent-filter>

<Action android: name = "android. intent. action. MY_BROADCAST"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

After the above information is configured, as long as it is broadcast of the android. intent. action. MY_BROADCAST address, MyReceiver can receive it. Note that this method of registration is resident. That is to say, when the application is closed, if the broadcast information is sent, MyReceiver will be called by the system and run automatically.

③ Register broadcast addresses dynamically for BroadcastReceiver: Dynamic Registration requires dynamically specifying broadcast addresses in the Code and registering them. Generally, we register a broadcast in Activity or Service, for example:

Public class MainActivity extends Activity {

Private MyReceiver myReceiver;

IntentFilter intentFilter;

@ Override

Protected void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. activity_main );

Mycycler = new mycycler ();

IntentFilter = new IntentFilter ();

IntentFilter. addAction ("android. intent. action. MY_BROADCAST ");

// RegisterReceiver is a method in the android. content. ContextWrapper class,

// Both Activity and Service inherit ContextWrapper, so you can directly call

RegisterReceiver (myReceiver, intentFilter );

}

}

In practical applications, we have registered a BroadcastReceiver in Activity or Service. If this Activity or Service is destroyed, the system reports an exception, prompt whether we forgot to cancel the registration. So remember to add:

@ Override

Protected void onDestroy (){

Super. onDestroy ();

UnregisterReceiver (myReceiver );

}

 

You can solve the problem. Note: This registration method is opposite to static registration, not resident, that is, broadcast will follow the life cycle of the program.

④ Send the broadcast, the Code is as follows:

Public void send (View v ){

Intent intent = new Intent ();

Intent. putExtra ("msg", "Hello, recipient ");

// SendBroadcast is also a method in the android. content. ContextWrapper class,

// It can send an Intent object with the specified address and parameter information in the form of Broadcast

SendBroadcast (intent );

}

⑤ Declare a button control in the layout file:

<Button

Android: id = "@ + id/button1"

Android: layout_width = "match_parent"

Android: layout_height = "wrap_content"

Android: text = "click send broadcast"/>

In MainActivity, obtain the button control object and register the listener. The Code is as follows:

Private Button button1;

Protected void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. activity_main );

Button1 = (Button) findViewById (R. id. button1 );

Button1.setOnClickListener (new OnClickListener (){

 

@ Override

Public void onClick (View v ){

Send (v );

}

});

}

3. Normal Broadcast and Ordered Broadcast)

Normal broadcast is completely asynchronous for multiple receivers. Generally, each receiver can receive the broadcast without waiting. The receiver does not affect each other. For such broadcast, the receiver cannot terminate the broadcast, that is, it cannot block the receiving actions of other receivers. We only need to create several different broadcast recipients and declare them. This is not demonstrated here.

Ordered broadcast is special. It is only sent to the receiver with a higher priority each time, and then the receiver with a higher priority spreads to the receiver with a lower priority. The receiver with a higher priority can terminate the broadcast.

Example:

FirstReceiver. java

Public class FirstReceiver extends BroadcastReceiver {

@ Override

Public void onReceive (Context context, Intent intent ){

String msg = intent. getStringExtra ("msg ");

Toast. makeText (context, msg, Toast. LENGTH_LONG). show ();

Bundle bundle = new Bundle ();

/**

* Use the setResultExtras method to set a Bundle object as a result set object and pass it to the next receiver,

* In this way, the receiver with a lower priority can use getResultExtras to obtain the latest processed information set.

*/

Bundle. putString ("msg", "FirstReceiver:" + msg );

SetResultExtras (bundle );

}

 

}

SecondReceiver

Public class SecondReceiver extends BroadcastReceiver {

 

@ Override

Public void onReceive (Context context, Intent intent ){

String msg = getResultExtras (true). getString ("msg ");

Toast. makeText (context, msg, Toast. LENGTH_LONG). show ();

Bundle bundle = new Bundle ();

Bundle. putString ("msg", msg );

SetResultExtras (bundle );

}

 

}

ThirdReceiver. java

Public class ThirdReceiver extends BroadcastReceiver {

 

@ Override

Public void onReceive (Context context, Intent intent ){

String msg = getResultExtras (true). getString ("msg ");

Toast. makeText (context, msg, Toast. LENGTH_LONG). show ();

}

 

}

Now, we need to register the broadcast address for the three receivers. Let's modify the AndroidMainfest. xml file:

<Cycler android: name = ". FirstReceiver">

<Intent-filter android: priority = "999">

<Action android: name = "android. intent. action. MY_BROADCAST"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

<Cycler android: name = ". SecondReceiver">

<Intent-filter android: priority = "888">

<Action android: name = "android. intent. action. MY_BROADCAST"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

<Cycler android: name = ". ThirdReceiver">

<Intent-filter android: priority = "777">

<Action android: name = "android. intent. action. MY_BROADCAST"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

We can see that the <intent-filter> of the three receivers has an android: priority attribute, which is reduced in turn. This attribute ranges from-1000 to 1000. A greater value indicates a higher priority.

Now, we need to modify the broadcast sending Code as follows:

Public void send (View v ){

Intent intent = new Intent ();

Intent. putExtra ("msg", "Hello, recipient ");

// SendBroadcast is also a method in the android. content. ContextWrapper class,

// It can send an Intent object with the specified address and parameter information in the form of Broadcast

// SendBroadcast (intent );

SendOrderedBroadcast (intent, "rookie. permission. MY_BROADCAST_PERMISSION ");

}

Note: When the sendOrderedBroadcast method is used to send an ordered broadcast, a permission parameter is required. If it is null, the recipient is not required to declare the specified permission. If it is not null, it indicates that if the recipient wants to receive the broadcast, the specified permission must be declared. This is from the security perspective. For example, system text messages are in the form of ordered broadcasting. An application may be capable of intercepting spam messages, when a text message arrives, it can receive the text message broadcast first. If necessary, the broadcast transmission is terminated. Such software must declare the permission to receive the text message.

Therefore, we define a permission in AndroidMainfest. xml:

<Permission android: protectionLevel = "normal" android: name = "rookie. permission. MY_BROADCAST_PERMISSION"/>

Then the permission is declared:

<Uses-permission android: name = "rookie. permission. MY_BROADCAST_PERMISSION"/>

In ordered broadcast, we can terminate broadcast transmission through the abortBroadcast () method;

4. Application Example of the broadcast Receiver

1. Start the service

We often have such applications, such as the message PUSH Service, which must be enabled upon startup. To implement this function, we can subscribe to the Broadcast System "Startup complete". After receiving this broadcast, we can start our own services.

The Code is as follows:

Public class MyReceiver extends BroadcastReceiver {

 

@ Override

Public void onReceive (Context context, Intent intent ){

Intent service = new Intent (context, MsgPushService. class );

Context. startService (service );

}

 

}

 

Public class MsgPushService extends Service {

 

@ Override

Public void onCreate (){

Super. onCreate ();

}

@ Override

Public int onStartCommand (Intent intent, int flags, int startId ){

Return super. onStartCommand (intent, flags, startId );

 

}

@ Override

Public IBinder onBind (Intent intent ){

Return null;

}

 

}

Then we need to configure the relevant information in AndroidManifest. xml:

<! -- Broadcast receiver on startup -->

<Cycler android: name = ". mycycler">

<Intent-filter>

<! -- Register the boot broadcast address -->

<Action android: name = "android. intent. action. BOOT_COMPLETED"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

<Service android: name = ". MsgPushService"/>

From the security perspective, the system requires that you have the permission to receive the boot broadcast, So we then declare the following permissions:

<Uses-permission android: name = "android. permission. RECEIVE_BOOT_COMPLETED"/>

2. Network status changes

In some cases, for example, when a user browses network information, the network is suddenly disconnected. We should promptly remind the user that the network is disconnected. To implement this function, we can receive a broadcast that changes the network status. When the connection status changes to the disconnected status, the system will send a broadcast. After receiving the broadcast, then, perform operations based on the network status. The following describes how to implement this function:

Public class MyReceiver extends BroadcastReceiver {

 

@ Override

Public void onReceive (Context context, Intent intent ){

If (! IsNetworkAvailable (context )){

Toast. makeText (context, "cannot connect to the network", 0). show ();

}

}

 

Private boolean isNetworkAvailable (Context context ){

ConnectivityManager cm = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE );

NetworkInfo [] info = cm. getAllNetworkInfo ();

If (info! = Null ){

For (int I = 0; I <info. length; I ++ ){

If (info [I]. getState () = NetworkInfo. State. CONNECTED ){

Return true;

}

}

}

Return false;

}

 

}

 

Register the receiver information again:

<Cycler android: name = ". mycycler">

<Intent-filter>

<Action android: name = "android.net. conn. CONNECTIVITY_CHANGE"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

Because we use network status-related APIs in the isNetworkAvailable method, we need to declare the relevant permissions. The following is the corresponding permission statement:

<Uses-permission android: name = "android. permission. ACCESS_NETWORK_STATE"/>

3. Power Change

If we read the software, it may be full screen reading. At this time, the user will not be able to see the remaining power, and we will be able to provide them with power information. To achieve this, we need to receive a broadcast of power changes and then obtain the percentage information. This sounds simple, and we will achieve the following:

Public class MyReceiver extends BroadcastReceiver {

 

@ Override

Public void onReceive (Context context, Intent intent ){

// Current power

Int currLevel = intent. getIntExtra (BatteryManager. EXTRA_LEVEL, 0 );

// Total power

Int total = intent. getIntExtra (BatteryManager. EXTRA_SCALE, 1 );

Int percent = currLevel * 100/total;

}

 

}

Then register the broadcast address information:

<Cycler android: name = ". mycycler">

<Intent-filter>

<Action android: name = "android. intent. action. BATTERY_CHANGED"/>

<Category android: name = "android. intent. category. DEFAULT"/>

</Intent-filter>

</Cycler>

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.