我正在使用 android studio,我在我的应用程序中实现广播,以便它应该只触发一个应用程序,我正在使用 Localbroadcastmanager 进行注册和注销
Android Phone
APP1 APP2
My Modules
我已将MyModules与安装在一部 Android 手机中的两个应用程序集成。
当我从其他 Android 手机向APP1发送消息时,它会接收到 APP1 的消息但APP1和APP2同时触发通知。
我的广播服务.java
public static void sendNotificationBroadcast(Context context, Message message) {
Log.i(TAG, "Sending notification broadcast...");
Intent notificationIntent = new Intent();
notificationIntent.putExtra(MyConstants.MESSAGE_JSON_INTENT, GsonUtils.getJsonFromObject(message, Message.class));
notificationIntent.setAction("com.notification.send");
context.sendBroadcast(notificationIntent);
}
我正在设置我的意图操作“com.notification.send”
AndroidManifest.xml
<receiver android:name="com.notification.NotificationBroadcastReceiver" android:exported="false">
<intent-filter>
<action android:name="com.notification.send"/>
</intent-filter>
</receiver>
这是我的NotificationBroadcastReceiver.java
public class NotificationBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "NotificationBroadcastReceiver";
private static String NOTIFICATION_ICON_METADATA = "com.notification.icon";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Integer notificationIconId = Utils.getMetaDataValueForResources(context, NOTIFICATION_ICON_METADATA);
String messageJson = intent.getStringExtra(Constants.MESSAGE_JSON_INTENT);
Log.i(TAG, "Received broadcast, action: " + action + ", message: " + messageJson);
if (!TextUtils.isEmpty(messageJson)) {
final Message message = (Message) GsonUtils.getObjectFromJson(messageJson, Message.class);
final NotificationService notificationService =
new NotificationService(notificationIconId == null ? R.drawable.ic_launcher : notificationIconId, context, R.string.wearable_action_label, R.string.wearable_action_title, R.drawable.ic_action_send);
final Contact contact = new contactService(context).getContactById(message.getIds());
new Thread(new Runnable() {
@Override
public void run() {
notificationService.notifyUser(contact, message);
}
}).start();
}
}
}
两个应用都在收听同一个广播,如何解决这个问题?
提前致谢
我通过使用 context.getPackageName() 解决了这个问题,我已经附加了我的操作
广播服务.java
intent.setAction(context.getPackageName()+".send");
AndroidManifest.xml
<intent-filter>
<action android:name="YOUR ANDROID APP PACKAGENAME.send"/>
</intent-filter>