Android - 广播机制

广播:可以理解为消息队列,又可细分为无序广播(异步的标准广播)、有序广播(同步的)。

使用步骤:

  1. 定义广播接收器
public class OrderBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "有序广播接收器接收信息成功!", Toast.LENGTH_LONG).show();
    }

}
  1. 注册接收器(AndroidManifest.xml)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">

        <receiver android:name=".broadcasts.OrderBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.myapplication.broadcasts.MY_ORDER_BROADCAST" />
            intent-filter>
        receiver>
        
    application>

manifest>
  1. 定义广播发送器
public class OrderBroadcastSender extends AppCompatActivity {

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

        Button btn = findViewById(R.id.send_order_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.myapplication.broadcasts.MY_ORDER_BROADCAST");
                // 安卓版本7以上都要加包裹名,主要包裹名是三层包裹,com.example.myapplication
                intent.setPackage(getPackageName());
                sendOrderedBroadcast(intent, null);
            }
        });
    }
}
  • 有序广播也无序广播就是在发送器那里调用不同的send而已
    • 有序:sendOrderedBroadcast(intent, null);
      • 在注册接收器设置不同的优先级,达到不同的接收顺序
<receiver android:name=".broadcasts.OrderBroadcastReceiver"
        android:enabled="true"
        android:exported="true">
      <intent-filter android:priority="1">
          <action android:name="com.example.myapplication.broadcasts.MY_ORDER_BROADCAST" />
      intent-filter>
 receiver>
	- 中断下级传播:abortBroadcast();
		
- 无序:sendBroadcast(intent);

你可能感兴趣的:(android)