FMUSER Wirless Transmit Video And Audio More Easier !

[email protected] WhatsApp +8618078869184
Language

    Detailed explanation of Broadcast in Android

     

    Broadcasting is divided into two different types: "Normal broadcasts" and "Ordered broadcasts". Ordinary broadcast is completely asynchronous and can be received by all broadcast receivers at the same time (logically). The efficiency of message delivery is relatively high, but the disadvantage is that the receiver cannot pass the processing result to the next receiver, and it cannot be terminated. Broadcast Intent propagation; however, ordered broadcast is based on the priority declared by the receiver (declared in the android:priority attribute of the intent-filter element, the larger the number, the higher the priority, the value range: -1000 to 1000. It is also possible Call the setPriority() of the IntentFilter object to set), and the recipient receives the broadcast in turn. For example, if the level of A is higher than that of B, and the level of B is higher than C, then the broadcast is first transmitted to A, then to B, and finally to C. After A gets the broadcast, it can store data in the broadcast. When the broadcast is sent to B, B can get the data stored by A from the broadcast.

     

    Context.sendBroadcast()

       What is sent is an ordinary broadcast, and all subscribers have the opportunity to obtain and process it.

     

    Context.sendOrderedBroadcast()

       Sending is an orderly broadcast. The system will execute the receivers one by one according to the priority declared by the receiver. The previous receiver has the right to terminate the broadcast (BroadcastReceiver.abortBroadcast()). If the broadcast is terminated by the previous receiver, the latter The receiver can no longer get the broadcast. For ordered broadcast, the previous receiver can store the processing result in the broadcast Intent, and then pass it to the next receiver.

     
    Broadcast receiver (BroadcastReceiver) is used to receive broadcast Intent, and the sending of broadcast Intent is realized by calling Context.sendBroadcast() and Context.sendOrderedBroadcast(). Usually a broadcast Intent can be received by multiple broadcast receivers subscribed to this Intent. This feature is similar to Topic message receivers in JMS. To implement a broadcast receiver method is as follows:

     

    The first step: define the broadcast receiver, inherit BroadcastReceiver, and rewrite the onReceive() method.

    public class IncomingSMSReceiver extendsBroadcastReceiver {
      @Override public void onReceive(Contextcontext, Intentintent) {
      }
    }

     

    Step 2: Subscribe to the broadcast Intent of interest, there are two subscription methods:

    The first type: use code to subscribe (dynamic subscription)

    IntentFilter filter = newIntentFilter("android.provider.Telephony.SMS_RECEIVED");
    IncomingSMSReceiver receiver = newIncomingSMSReceiver();
    registerReceiver(receiver, filter);

     

    The second type: Subscribe in the <application> node in the AndroidManifest.xml file (static subscription)

    <receiver android:name=".IncomingSMSReceiver">
       <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
       </intent-filter>
    </receiver>


    Let's take a look at the difference between dynamic broadcast subscription and static broadcast subscription:
    Static subscription broadcast is also called: resident broadcast. When your application is closed, if there is a broadcast message, the broadcast receiver you wrote can also receive it. Its registration method is AndroidManifast in your application. .xml for subscription.

     

    Dynamic subscription broadcast is also called: non-resident broadcast. When the application ends, the broadcast will naturally disappear. For example, you subscribe to the broadcast in onCreate or onResume in the activity, and you must cancel the broadcast subscription in onDestory or onPause. Otherwise, an exception will be reported, so your broadcast receiver will be a non-resident.

     

    There is one more detail here that is the two subscription methods. When sending broadcasts, you need to pay attention to: The implicit intent method is used for dynamic registration, so you need to use implicit intent to send when sending broadcasts. , Otherwise the broadcast receiver will not be able to receive the broadcast. Pay attention to this point. But when subscribing statically, because it is subscribed in AndroidMainfest.xml, it is possible to use display Intent and implicit Intent when sending broadcasts (of course this is only for broadcast receivers defined by ourselves), so just in case , We generally use implicit Intent to send broadcast.

     

    Let's look at an example:

    Take a look at the project structure:

     

    Take a look at the static subscription broadcast:
    package com.broadcast.demo;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;

    import com.example.androidbroadcastdemo.R;

    /**
     * Static subscription broadcast
     * @author weijiang204321
     *
     */
    public class StaticRegisterBroadcastActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn = (Button)findViewById(R.id.btn);
    To
    btn.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
    //Use a static way to register the broadcast, you can use the display intent to send the broadcast
    Intent broadcast = new Intent("com.broadcast.set.broadcast");
    sendBroadcast(broadcast,null);
    }
    To
    });
    }
    To
    }


    Subscribe in AndroidMainfest.xml:


    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="
    http://schemas.android.com/apk/res/android"
        package="com.example.androidbroadcastdemo"
        android:versionCode="1"
        android:versionName="1.0">

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="18" />
       
        <!-- Permission -->
        <uses-permission android:name="android.permission.RECEIVE_SMS"/>
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.SEND_SMS"/>
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
            <activity
                android:name="com.broadcast.demo.StaticRegisterBroadcastActivity"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
           
            <!-- Unordered broadcast registration START -->
            <receiver android:name="com.broadcast.receiver.UnSortBroadcastReceiver">
                <intent-filter>
                    <action android:name="com.broadcast.demo.mybroadcast"/>
                </intent-filter>
            </receiver>
            <!-- Unordered broadcast registration END -->
           
            <!-- Registration of orderly broadcast START -->
            <receiver android:name="com.broadcast.receiver.SortBroadcastReceiverA">
                <intent-filter android:priority="999">
                    <action android:name="com.broadcast.set.broadcast"/>
                </intent-filter>
            </receiver>
           
            <!-- Receive SMS broadcast -->
            <receiver android:name="com.broadcast.receiver.SortBroadcastReceiverB">
                <intent-filter android:priority="1000">
                    <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
                </intent-filter>
            </receiver>
            <!-- Registration of orderly broadcast END -->
           
            <!-- Service for uploading SMS content -->
            <service android:name="com.broadcast.service.UploadSMSService">
                <intent-filter>
                    <action android:name="com.broadcast.service.uploadsmsservice"/>
                </intent-filter>
            </service>
           
        </application>

    </manifest>

    Don't worry about the other content for now, as we will talk about later, here we only focus on the registration of static broadcasts

    <!-- Unordered broadcast registration START -->
           <receiver android:name="com.broadcast.receiver.UnSortBroadcastReceiver">
                <intent-filter>
                    <action android:name="com.broadcast.demo.mybroadcast"/>
                </intent-filter>
            </receiver>
    <!-- Unordered broadcast registration END -->


    Let's take a look at the receiver of the broadcast:

    package com.broadcast.receiver;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;

    /**
     * Broadcast receiver
     * @author weijiang204321
     *
     */
    public class UnSortBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    Log.e("Intent_Action:",intent.getAction()+"");
    }

    }
    The logic in the onReceive method in the broadcast receiver is very simple, which is to print the content of the Action.
    Run the program, the result is very simple, here is not the picture.

     

    Let’s take a look at dynamic subscriptions:


    package com.broadcast.demo;

    import android.app.Activity;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;

    import com.broadcast.receiver.UnSortBroadcastReceiver;
    import com.example.androidbroadcastdemo.R;

    /**
     * Use dynamic way to register broadcast
     * @author weijiang204321
     *
     */
    public class DynamicRegisterBroadcastActivity extends Activity {
    To
    public static final String NEW_LIFEFORM_DETECTED = "com.dxz.broadcasttest.NEW_LIFEFORM";
    protected UnSortBroadcastReceiver receiver;
    To
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn0 = (Button) findViewById(R.id.btn);
    btn0.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    //Send broadcast
    Intent it = new Intent(NEW_LIFEFORM_DETECTED);
    sendBroadcast(it);
    }
    });
    }

    @Override
    protected void onResume() {
    super.onResume();
    //Register for broadcast
    IntentFilter counterActionFilter = new IntentFilter(NEW_LIFEFORM_DETECTED);
    receiver = new UnSortBroadcastReceiver();
    registerReceiver(receiver, counterActionFilter);
    }

    @Override
    protected void onPause() {
    super.onPause();
    //Cancel broadcast
    unregisterReceiver(receiver);
    }
    }
    Here we are subscribing to broadcasting in onResume, and unsubscribing to broadcasting in onPause.
    Change the launched Activity to DynamicRegisterBroadcastActivity in AndroidMainfest.xml. The other content does not need to be modified. Run the program and print the result is very simple, so I won’t see the picture here.

     

    Let’s take a look at ordered broadcasting and unordered broadcasting

    We have already mentioned this at the beginning, let's take a look at disordered broadcasting:

    First we define two broadcast receivers:

    The first broadcast receiver:


    package com.broadcast.receiver;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;

    /**
     * Broadcast receiver A
     * @author weijiang204321
     *
     */
    public class SortBroadcastReceiverA extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
    Log.e("Demo:","broadcast receiver A");
    }

    }
    The second broadcast receiver:

    package com.broadcast.receiver;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;

    /**
     * Broadcast receiver B
     * @author weijiang204321
     *
     */
    public class SortBroadcastReceiverB extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
    Log.e("Demo:","Broadcast B");
    }

    To
    To
    }


    Subscribe to broadcast in AndroidMainfest.xml


     <receiver android:name="com.broadcast.receiver.SortBroadcastReceiverA">
                <intent-filter android:priority="999">
                    <action android:name="com.broadcast.set.broadcast"/>
                </intent-filter>
    </receiver>
           
    <receiver android:name="com.broadcast.receiver.SortBroadcastReceiverB">
                <intent-filter android:priority="1000">
                    <action android:name="com.broadcast.set.broadcast"/>
                </intent-filter>
    </receiver>
    operation result:


    The running result is a bit strange. Why is receiver B in the front and receiver A in the back? The reason is that when we subscribe to the broadcast in AndroidMainfest.xml, we set the android:priority attribute value in the intent-filter. The larger the value, the higher the priority. , The priority of receiver B is 1000, the priority of receiver A is 999, so B receives the broadcast first, and then A receives it, but there is no connection between receiver B and receiver A, and there can be no interaction Yes, because this is an out-of-order broadcast and asynchronous, we can do an experiment by adding code to the onReceiver method in B:

    abortBroadcast();//Terminate the transmission of this broadcast

    operation result:

     

    We can see the prompt error, that is, non-ordered broadcast is not allowed to terminate the broadcast. In fact, termination is useless, because receiver A still receives the broadcast.

     

    Let's take a look at orderly broadcasting, the code needs to be modified:

    The first is when sending a broadcast:


    Intent broadcast = new Intent("com.broadcast.set.broadcast");
    sendOrderedBroadcast(broadcast,null);
    Then add a method to terminate the broadcast in the B receiver:
    abortBroadcast();

    The other code does not need to be modified, the operation result:

     

    There is only receiver B, receiver A does not receive the broadcast, because the broadcast is terminated in receiver B, and the subsequent receivers cannot accept it.

    Modify the code below:

    Recipient B:


    package com.broadcast.receiver;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;

    /**
     * Broadcast receiver B
     * @author weijiang204321
     *
     */
    public class SortBroadcastReceiverB extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
    Log.e("Demo:","broadcast receiver B");
    Bundle bundle = new Bundle();
    bundle.putString("next_receiver", "next broadcast receiver");
    setResultExtras(bundle);
    }
    To
    }
    After B receives the broadcast, it stores some value and passes it to the next receiver.


    Receiver A's code:


    package com.broadcast.receive

     

     

     

     

    List all Question

    Nickname

    Email

    Questions

    Our other product:

    Professional FM Radio Station Equipment Package

     



     

    Hotel IPTV Solution

     


      Enter email  to get a surprise

      fmuser.org

      es.fmuser.org
      it.fmuser.org
      fr.fmuser.org
      de.fmuser.org
      af.fmuser.org ->Afrikaans
      sq.fmuser.org ->Albanian
      ar.fmuser.org ->Arabic
      hy.fmuser.org ->Armenian
      az.fmuser.org ->Azerbaijani
      eu.fmuser.org ->Basque
      be.fmuser.org ->Belarusian
      bg.fmuser.org ->Bulgarian
      ca.fmuser.org ->Catalan
      zh-CN.fmuser.org ->Chinese (Simplified)
      zh-TW.fmuser.org ->Chinese (Traditional)
      hr.fmuser.org ->Croatian
      cs.fmuser.org ->Czech
      da.fmuser.org ->Danish
      nl.fmuser.org ->Dutch
      et.fmuser.org ->Estonian
      tl.fmuser.org ->Filipino
      fi.fmuser.org ->Finnish
      fr.fmuser.org ->French
      gl.fmuser.org ->Galician
      ka.fmuser.org ->Georgian
      de.fmuser.org ->German
      el.fmuser.org ->Greek
      ht.fmuser.org ->Haitian Creole
      iw.fmuser.org ->Hebrew
      hi.fmuser.org ->Hindi
      hu.fmuser.org ->Hungarian
      is.fmuser.org ->Icelandic
      id.fmuser.org ->Indonesian
      ga.fmuser.org ->Irish
      it.fmuser.org ->Italian
      ja.fmuser.org ->Japanese
      ko.fmuser.org ->Korean
      lv.fmuser.org ->Latvian
      lt.fmuser.org ->Lithuanian
      mk.fmuser.org ->Macedonian
      ms.fmuser.org ->Malay
      mt.fmuser.org ->Maltese
      no.fmuser.org ->Norwegian
      fa.fmuser.org ->Persian
      pl.fmuser.org ->Polish
      pt.fmuser.org ->Portuguese
      ro.fmuser.org ->Romanian
      ru.fmuser.org ->Russian
      sr.fmuser.org ->Serbian
      sk.fmuser.org ->Slovak
      sl.fmuser.org ->Slovenian
      es.fmuser.org ->Spanish
      sw.fmuser.org ->Swahili
      sv.fmuser.org ->Swedish
      th.fmuser.org ->Thai
      tr.fmuser.org ->Turkish
      uk.fmuser.org ->Ukrainian
      ur.fmuser.org ->Urdu
      vi.fmuser.org ->Vietnamese
      cy.fmuser.org ->Welsh
      yi.fmuser.org ->Yiddish

       
  •  

    FMUSER Wirless Transmit Video And Audio More Easier !

  • Contact

    Address:
    No.305 Room HuiLan Building No.273 Huanpu Road Guangzhou China 510620

    E-mail:
    [email protected]

    Tel / WhatApps:
    +8618078869184

  • Categories

  • Newsletter

    FIRST OR FULL NAME

    E-mail

  • paypal solution  Western UnionBank OF China
    E-mail:[email protected]   WhatsApp:+8618078869184   Skype:sky198710021 Chat with me
    Copyright 2006-2020 Powered By www.fmuser.org

    Contact Us