[Android Getting Started to Project Combat -- 5.2] —— Broadcasting (2): Custom Broadcasting and Local Broadcasting

Table of contents

1. Send a custom broadcast

1. Send standard broadcast

2. Send orderly broadcast

1) Set orderly broadcast

       2) So how to set the priority?

3) Whether to allow the broadcast to continue to pass

2. Use local broadcasting


        Continuing from the previous article ( if necessary, please move ), we learned about sending system broadcasts above, and then learned about custom and local broadcasts.

1. Send a custom broadcast

1. Send standard broadcast

        First define a broadcast receiver ready to receive standard broadcasts.

        Create a new MyBroadcastReceiver class with the following code:

public class MyBroadcastReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent){
        Toast.makeText(context, "接收到广播", Toast.LENGTH_SHORT).show();
    }
}

        Then modify the broadcast receiver in AndroidManifest.xml.

        Let MyBroadcastReceiver receive a broadcast whose value is com.example.broadcasttest.MY_BROADCAST. When sending a broadcast later, it needs to send such a broadcast.

  ..........
 <receiver
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
...........

        Modify the activity_main.xml code as follows:

        A button is added here for sending broadcasts.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送广播"/>

    

</LinearLayout>

        Modify the MainActivity code as follows:

        The logic of sending a custom broadcast is added to the click event of the button, an Intent object is constructed, the value of the broadcast to be sent is passed in, and the sendBroadcast() method of the Context is called to send the broadcast. In this way, all broadcast receivers listening to the com.example.broadcasttest.MY_BROADCAST broadcast will receive the message.

        Since the broadcast is delivered by Intent, some data can also be carried in the Intent and delivered to the broadcast receiver.

public class MainActivity extends AppCompatActivity {
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });


    }

}

The effect is as follows:

 

2. Send orderly broadcast

1) Set orderly broadcast

First modify the code of MainActivity as follows:

        It can be seen that to send an ordered broadcast, you only need to modify one line of code. The sendOrderedBroadcast() method has two parameters, the first is Intent, and the second is a string related to permissions.

 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendOrderedBroadcast(intent,null);
            }
        });

        After running the program, it is found that the effect is the same as before. The difference is that the broadcast receivers are in order at this time, and the previous broadcast receivers can truncate the broadcast .

       2) So how to set the priority?

        set in the registration;

        Modify the code of AndroidManifest.xml as follows:

        Here the priority is set to 100.

.................
<receiver
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="100">
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
...................

        

3) Whether to allow the broadcast to continue to pass

Modify the MyBroadcastReceiver code as follows:

        The abortBroadcast() method means to truncate this broadcast, and subsequent broadcast receivers can no longer receive this broadcast.

public class MyBroadcastReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent){
        Toast.makeText(context, "接收到广播", Toast.LENGTH_SHORT).show();
        abortBroadcast();
    }
}

2. Use local broadcasting

        The broadcasts used above are all system global broadcasts, that is, the broadcasts sent out can be received by any other application, and we can also receive broadcasts from any other application, which is easy to cause security problems, such as: some of the broadcasts we send carry The broadcast of data may be intercepted by other applications, or other programs keep sending us various garbage broadcasts.

        In order to solve the above problems, Anroid introduces a set of local broadcast mechanism, and broadcasts sent using this mechanism can only be transmitted inside the application .

Let's try to implement it.

Modify the MainActivity code as follows:

        Basically the same as the previous dynamic registration broadcast listener.

public class MainActivity extends AppCompatActivity {
    
    private IntentFilter intentFilter;
    
    private LocalReceiver localReceiver;
    
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = localBroadcastManager.getInstance(this);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册本地广播监听器
        
    }
    
    protected void onDestroy(){
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    class LocalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "收到本地广播", Toast.LENGTH_SHORT).show();

        }
    }

}

        Note: Local broadcasts cannot be received through static registration.

Guess you like

Origin blog.csdn.net/Tir_zhang/article/details/130140869