注册静态广播之后无法接收到发送的广播
xml中注册广播
<receiver android:name=".GlobalBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.GLOBAL_BUTTON"/>
</intent-filter>
</receiver>
创建广播接收器
public class GlobalBroadcastReceiver extends BroadcastReceiver
{
private static final String TAG = "GlobalBroadcastReceiver ";
@Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "onReceive");
}
}
问题在创建好之后没有收到广播
原因是没有指定具体的接收器路径
String receiverPath = "com.android.launcher3.GlobalBroadcastReceiver";
Intent intent = new Intent("android.intent.action.GLOBAL_BUTTON"); // 创建一个指定动作的意图
// 发送静态广播之时,需要通过setComponent方法指定接收器的完整路径
ComponentName componentName = new ComponentName(this, receiverPath);
intent.setComponent(componentName); // 设置意图的组件信息
sendBroadcast(intent); // 发送静态广播
Toast.makeText(this, "已发送广播", Toast.LENGTH_SHORT).show();
也可通过adb命令发送广播:
adb shell am broadcast -a android.intent.action.GLOBAL_BUTTON -n com.android.launcher3/.GlobalBroadcastReceiver
本文讲述了在Android中注册静态广播后未接收到广播的问题,原因在于没有正确设置接收器路径。作者详细介绍了如何通过`setComponent`方法指定接收器完整路径,并提供了使用adb命令发送广播的方法。

2793

被折叠的 条评论
为什么被折叠?



