发送&接收自定义广播

新建广播接收器

public class MyBroadcastReceiver extends BroadcastReceiver {

    private final String TAG = "MyBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "广播已接收");
        Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
    }
}

在Manifest中注册

放在application标签中

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

在MainActivity中编写发送广播按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/send_broadcast_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"
        />

  </LinearLayout>
public class MainActivity extends AppCompatActivity {

    /**
     * 意图过滤器,当我们隐式的启动系统组件的时候,就会根据IntentFilter来筛选出合适的进行启动
     */
    private IntentFilter intentFilter;

    private final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendBroadcastBtn = findViewById(R.id.send_broadcast_btn);
        sendBroadcastBtn.setOnClickListener(v -> {
            Intent intent = new Intent("com.example.mybroadcast.My_BROADCAST");
            intent.setComponent(
                    new ComponentName("com.example.mybroadcast", //接收器包名
                            "com.example.mybroadcast.MyBroadcastReceiver") //接收器包名+类名
            );
            sendBroadcast(intent); //发送广播
            Log.d(TAG, "广播已发送");
        });
    }

}
posted @ 2022-08-06 19:16  jarico  阅读(57)  评论(0)    收藏  举报