Android Basics - BroadcastReceiver of the Four Components

Android Basics - BroadcastReceiver of the Four Components

definition

Broadcast(广播): a mechanism widely used to transfer information between applications;

BroadcastReceiver(广播接收器): A component that receives and responds to broadcasts from the system and other applications.

register

1. Define the broadcast receiver

Inheritance BroadcastReceiver, implement custom broadcast receiver, implement onReceive()method to accept broadcast

public class ExampleBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = ExampleBroadcastReceiver.class.getSimpleName();
    
    private static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (ACTION_BOOT.equals(intent.getAction())) {
            Log.i(TAG, "receive boot completed broadcast");
            Toast.makeText(context, "system boot completed.", Toast.LENGTH_LONG).show();
        }
    }
}
复制代码

When the onReceive()method is executed, ExampleBroadcastReceiverthe end of the life cycle may be recycled by the system, so onReceive()asynchronous operation is not recommended; in addition, due to the ANR limitation, the onReceive()method must be executed within 10 seconds.

2. Static registration

Register in AndroidManifest.xml

<manifest ...>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
	<application ...>
	    <receiver
            android:name=".broadcast.ExampleBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
	</application>
</manifest>   
复制代码
  • The broadcast is registered in a static way, and the broadcast can be received even if the application is not started, so the broadcast can be used as the self-starting and keep-alive mechanism of the application.
  • android:name: Represents a custom broadcast receiver class
  • action: specifies the type of broadcast received, here means accepting the system startup broadcast
  • uses-permission: declares that we need to use the permission to receive the power-on state

3. Dynamic registration

public class ExampleActivity extends AppCompatActivity {
    private ExampleBroadcastReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myReceiver = new ExampleBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.BOOT_COMPLETED");
        registerReceiver(myReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }
}
复制代码
  • Register the broadcast in the Activity and specify the type of broadcast to monitor; finally onCreate()turn off the broadcast monitorregisterReceiver在onDestory()
  • Dynamically register broadcasts, users can register when they need to use them, and turn off broadcast monitoring when they are no longer in use, which is more flexible in use

Classification

Broadcasts can be divided into unordered broadcasts (default), ordered broadcasts , local broadcasts , and sticky broadcasts .

out-of-order broadcast

Out-of- order broadcast is an asynchronous execution method. All broadcast receivers can receive the broadcast at the same time. There is no sequence. The broadcast ends when no receivers accept the broadcast.

  • send broadcast

    public void sendCustomBroadcast(View view){      
      Intent intent = new Intent("com.example.broadcast");     
      sendBroadcast(intent);
    }
    复制代码

ordered broadcast

有序广播是一种同步执行方式,广播发送之后,同一时刻只会有一个广播接收者在执行广播接收,广播执行者按照优先级顺序进行广播接收,而且在接收的过程中可以截断广播,后面的接收者就无法再接收到该广播。

  • 声明广播接收者优先级

    <manifest ...>
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    	<application ...>
    	    <receiver
                android:name=".broadcast.ExampleBroadcastReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter android:priority="100">
                    <action android:name="com.example.broadcast"/>
                </intent-filter>
            </receiver>
    	</application>
    </manifest>  
    复制代码

    IntentFilter中通过android:priority指定优先级,值越大优先级越高

  • 发送广播

    public void sendOrderBroadcast(View view){      
      Intent intent = new Intent("com.example.broadcast");     
      sendOrderBroadcast(intent);
    }
    复制代码
  • 截断广播

     @Override
    public void onReceive(Context context, Intent intent) {
        abortBroadcast();
    }
    复制代码

    在广播接收者的onReceive()方法中,可以通过调用abortBroadcast()方法截断广播,优先级较低的广播接收者就无法再接收到该广播

本地广播

本地广播是一种局部广播,只能在本应用内部传播,广播接收者也只能接收本应用内部的广播,由于这一特点,所以本地广播不支持静态注册方式。

  • 注册本地广播接收者

    public class ExampleActivity extends AppCompatActivity {
        private ExampleBroadcastReceiver myReceiver;
        
        private LocalBroadcastManager localBroadcastManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            myReceiver = new ExampleBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.intent.action.BOOT_COMPLETED");
            localBroadcastManager = LocalBroadcastManager.getInstance(this);
            localBroadcastManager.registerReceiver(intent, filter);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            localBroadcastManager.unregisterReceiver(myReceiver);
        }
    }
    复制代码

    通过LocalBroadcastManager.getInstance()或者本地广播管理的实例,使用该实例来注册广播接收者

  • 发送广播

    private void sendBroadcast() {
        Intent intent = new Intent("com.example.broadcast");     
    	localBroadcastManager.sendBroadcast(intent);
    }
    复制代码

粘性广播

前面了解了几种广播类型,我们可以知道,当所有广播接收者处理完广播接收之后则广播结束。也就是说,只有在发送前已完成注册的广播接收者才能接收到该广播。那么如果我们在某种情况下,广播接收者注册晚于广播发送时间,但是我们又想接收到该广播,该如何处理呢?这里就需要使用到粘性广播

  • 粘性广播在发送之后会保存刚发送过的广播,当有新注册的广播接收者注册后可以继续使用该广播,直到该广播被移除;

  • 粘性广播只会保存最后一次的广播,也就是说如果在某个广播接收者注册前,发送了多条同样的广播,那么广播接收者注册后只能接收到最后一条;

  • 粘性广播通过sendStickyBroadcast()发送广播,removeStickyBroadcast()移除广播,且需要添加权限<uses-permission android:name="android.permission.BROADCAST_STICKY"/>

Guess you like

Origin juejin.im/post/7080442423481991205