Android: Broadcast and androidbroadcast

Source: Internet
Author: User

Android: Broadcast and androidbroadcast

  • Concept of Broadcast
    • In reality: we often use radio stations to publish messages by sending broadcasts and buy a radio to listen to them.
    • Android: when the system sends a broadcast when an event is generated, the application uses the broadcast receiver to receive the broadcast and knows what event the system generates. During the running process, the Android system generates many events, such as startup, power change, sending and receiving text messages, making phone calls, and unlocking the screen.
  • Registration of broadcast recipients

    Four Android components must be registered in the configuration file.

    The broadcast receiver is special. It can be registered either in the list file or directly using code registration.

    Some broadcast recipients must register Code such as power change, screen lock and unlock

    • Use configuration in the configuration file

      <Receiver er android: name = "package of the broadcast receiving implementation class"> <intnt-filter> <android: name = "broadcast to be received"> <android: data = ""> ...... </intent-filter> </receiver ER>
    • Code Implementation

      // Create the broadcast receiver object receiver = new ScreenOnOffReceiver (); // use the IntentFilter object to specify the type of broadcast receiver IntentFilter = new IntentFilter (); filter. addAction (Intent. ACTION_SCREEN_OFF); filter. addAction (Intent. ACTION_SCREEN_ON); // register the broadcast receiver registerReceiver (receiver, filter );
    • After the broadcast receiver is removed from registration, the broadcast receiver will become ineffective.

      unregisterReceiver(receiver);
    • Why?
  • Broadcast Reception

    In Android, Broadcast is a widely used mechanism for transmitting information between applications. BroadcastReceiver is a type of component that filters and accepts and responds to Broadcast. BroadcastReceiver is used to receive the broadcast Intent. The broadcast Intent is sent by calling sendBroadcast/sendOrderedBroadcast. Generally, a broadcast Intent can be received by multiple broadcast recipients subscribed to this Intent.
  • Implement a BroadcastReceiver to receive broadcasts sent by BroadCast.

    Requirement: Listen to the user's call, and add 17951 before the user's call number.

    Intercepted broadcast:

    <action android:name="android.intent.action.NEW_OUTGOING_CALL"></action>

    Required permissions:

    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

    1. Create a new Android project IPCaller

    2. Create a new class IPCallerReceiver under the src directory to inherit BroadcastReceiver and override the OnReceive method.

    Public class IPCallReveiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {// obtain the call number String resultData = getResultData (); // Add 17951 before the phone number, and then return the data setResultData ("17951" + resultData );}}

    3. register the broadcast receiver in AndroidManifest. xml

    <receiver android:name="com.itheima.ipcaller.IPCallReveiver">    <intent-filter android:priority="1000">        <action android:name="android.intent.action.NEW_OUTGOING_CALL"></action>    </intent-filter></receiver>

    In the following configuration file, the <intent-filter android: priority = "1000"> attribute indicates setting the priority for the current receiver, the higher the priority, the higher the priority. Broadcast registration is only valid)

    Run the above Code, call 5556, and find that the dial number has changed to 179515556. Run the following command:

  • Send custom Broadcast

    • Send unordered Broadcast

      • Unordered broadcast cannot be intercepted. If intercepted, an error is returned:
      • Unordered broadcast can be considered as receiving broadcast at the same time by all broadcast recipients
      • Unordered broadcast is sent using the sendBroadcast method.

        Public void sendBroadcast (View view) {// define an Intent intent Intent = new intent (); // set Action to accept the Intent filter intent of the broadcast. setAction ("com. itheima. broadcast "); // bind the data intent. putExtra ("data", "I am unordered broadcast data"); // send unordered broadcast sendBroadcast (intent );}
    • Send ordered Broadcast

      • Ordered broadcast can be intercepted, and the receiver with a lower priority can be intercepted.
      • The value range of the broadcast recipient's priority is: 1000 (highest )~ -1000 (minimum)
      • In the same priority, the order of receipt depends on the declared order in the list file. The system first receives the broadcast.
      • Ordered broadcast is sent using the sendOrderedBroadcast () method. You can use the abortBroadcast () method to intercept * When the priority of the broadcast receiver can be declared in the list file, under the <intent-filter> label, set the "android: property" attribute.

      We create a new project to demonstrate the process of sending and receiving unordered broadcasts.

      2. Add a button in the default MainActivity layout to bind the event. The core function of this event is to send an ordered broadcast. The MainActivity code list is as follows:

      Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} public void sendOrder (View view) {// Intent intent Intent = new intent (); // define action Intent. setAction ("com. itheima. data "); // send ordered broadcast // The first parameter Intent type: Intent // The second parameter String type receiverPermission, the receiver required permissions // The third parameter BroadcastReceiver type, the self-defined receiver is used as the final receiver // Handler type, which is used to execute the callback of the receiver. If it is null, it is executed in the main thread // The Fifth parameter int type, result code initialization code // The sixth parameter initialization parameter // The Seventh parameter Bundle type, additional data sendOrderedBroadcast (intent, null, RESULT_ OK, "$10 thousand", null );}

      3. Write the MyReceiver and MyReceiver2 classes respectively, inherit the BroadcastReceiver class

      Mycycler class code list:

      Public class MyReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {String action = intent. getAction (); String resultData = getResultData (); Toast. makeText (context, "MyReceiver received" + action + "published broadcast:" + resultData, 1 ). show (); System. out. println ("MyReceiver received" + action + "published broadcast:" + resultData );}}

      List of MyReceiver2 types of code:

      Public class MyReceiver2 extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {String action = intent. getAction (); String resultData = getResultData (); Toast. makeText (context, "MyReceiver2 receives" + action + "published broadcast:" + resultData, 1 ). show (); System. out. println ("MyReceiver2 received" + action + "published broadcast:" + resultData );}}

      4. Register mycycler and MyReceiver2 in AndroidManifest. xml:

      <receiver android:name="com.itheima.broadcastAndreceiver.MyReceiver">    <intent-filter android:priority="1000">     <action android:name="com.itheima.data"></action>    </intent-filter></receiver><receiver android:name="com.itheima.broadcastAndreceiver.MyReceiver2">    <intent-filter android:priority="-1000">        <action android:name="com.itheima.data"></action>    </intent-filter></receiver>

      In the preceding configuration file, we set the highest priority of mycycler 1000 and MyReceiver2 the lowest priority of-1000.

      5. The following describes the receipt rules of ordered broadcast in minutes.

      Directly deploy the above project to the simulator and click send broadcast. The console result is:

      6. modify the code of the MyReceiver class: add the abortBroadcast () method to the onReceive method,

      Public class MyReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {String action = intent. getAction (); String resultData = getResultData (); Toast. makeText (context, "MyReceiver received" + action + "published broadcast:" + resultData, 1 ). show (); System. out. println ("MyReceiver received" + action + "published broadcast:" + resultData); abortBroadcast ();}}

      Re-deploy the project, run, and click send broadcast. In this case, the console prints the information

      This indicates that the broadcast receiver with a higher priority can modify or intercept the broadcast receiver with a lower priority to receive the modified broadcast or cannot receive the broadcast.

      7. In the second case, modify the sendOrder method in the MainActivity class, modify the third parameter in sendOrderedBroadcast, and specify a final receiver.

      Public void sendOrder (View view) {// Intent intent Intent = new intent (); Intent. setAction ("com. itheima. data "); sendOrderedBroadcast (intent, null, new MyReceiver2 (), null, RESULT_ OK," $10 thousand ", null );}

      To run the above project, we can output the following information on the console:

      Although we call the abortBroadcast (); Method in MyReceiver, the broadcast is still received by myreceiver2. The reason is that the sendOrderedBroadcast method specifies the MyReceiver2 receiver as the final receiver, so the MyReceiver2 receiver can still receive the broadcast when the broadcast is terminated.

      8. In 3rd cases, we modify the MyReceiver class and remove the abortBroadcast (); Method in the onReceive method in the class. Then run the above project. Enter the following information in the console:

      We found that MyReceiver receives the broadcast for the first time, MyReceiver2 receives the broadcast for the second time, and MyReceiver2 receives the broadcast again. Yes, the result is true, because we use MyReceiver2 as the final receiver in the sendOrderedBroadcast method, then the broadcast we send will be received by all qualified receivers, the final receiver specified at the end will still receive the message no matter whether it has received the message or not.

 

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.