<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edtMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/input_message"
android:singleLine="true"
android:textSize="20sp" />
<Button
android:id="@+id/btnSendBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="doSendBroadcast"
android:text="@string/send_broadcast"
android:textSize="20sp" />
</LinearLayout>
<resources>
<string name="app_name">发送与接收广播</string>
<string name="input_message">请输入要广播的消息</string>
<string name="send_broadcast">发送广播的消息</string>
</resources>
package net.xxr.sendreceivebroadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* 功能:自定义广播接收者
* 作者:小小榕
* 日期:2020年12月30日
*/
public class CustomReceiver extends BroadcastReceiver {
private final String TAG = "send_receive_broadcast"; // 标记
private final String INTENT_ACTION_SEND_MESSAGE = "net.xxr.intent.action.SEND_MESSAGE"; // 广播频道
@Override
public void onReceive(Context context, Intent intent) {
// 按照频道获取广播信息
if (intent.getAction().equals(INTENT_ACTION_SEND_MESSAGE)) {
// 获取广播信息
String message = intent.getStringExtra("message");
// 输出广播信息
Log.d(TAG, message);
}
}
}
package net.xxr.sendreceivebroadcast;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import net.xxr.sendreceivebroadcast.CustomReceiver;
import java.util.PrimitiveIterator;
public class MainActivity extends AppCompatActivity {
private final String TAG = "send_receive_broadcast";
private final String INTENT_SEND_MESSAGE = "net.xxr.intent.action.SEND_MESSAGE";
private EditText editMessage;
private int broadcastCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editMessage = findViewById(R.id.edtMessage);
CustomReceiver receiver = new CustomReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(INTENT_SEND_MESSAGE);
registerReceiver(receiver, filter);
}
/**
* 发布广播
*/
public void doSendBroadcast(View view) {
broadcastCount++;
String message = editMessage.getText().toString();
Intent intent = new Intent();
intent.setAction(INTENT_SEND_MESSAGE);
intent.putExtra("message","第" + broadcastCount + "次广播信息:" + message);
sendBroadcast(intent);
}
}