android自定义广播发送的时候,广播接收器无法接收到,最终排查下来是在发送的时候需要带上接收方的包名(android8以后)。
activity中发送自定义广播:
public class CustomBroadCastActivity extends AppCompatActivity {
private static final String TAG = "CustomBroadCast";
private Button mButton;
private EditText mEditText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_broadcast);
mButton = findViewById(R.id.broad_cast_bt);
mEditText = findViewById(R.id.broad_cast_et);
mButton.setOnClickListener((v -> {
Log.i(TAG, "onCreate: 发送广播动作触发");
String content = mEditText.getText().toString();
Intent intent = new Intent();
intent.setAction("com.example.CUSTOM_BROADCAST");
//需要设置接收方的包名,否则对方无法收到广播
intent.setPackage(this.getPackageName());
intent.putExtra("content", content);
sendBroadcast(intent);
}));
}
}
定义广播接收器
/**
* 接收自定义广播内容,在manifest.xml中静态注册
*/
public class CustomBroadCastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadCast";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String content = intent.getStringExtra("content");
Log.e(TAG, "onReceive: action is " + action + " content is " + content);
}
}
在manifest.xml中静态注册广播
<receiver
android:name="com.example.broadcastreceiver.CustomBroadCastReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.example.CUSTOM_BROADCAST" />
</intent-filter>
</receiver>
layout.xml资源文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/broad_cast_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入发送的广播内容"
android:textSize="30sp" />
<Button
android:id="@+id/broad_cast_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送广播"
android:textSize="30sp" />
</LinearLayout>