1

我正在使用 android studio,我在我的应用程序中实现广播,以便它应该只触发一个应用程序,我正在使用 Localbroadcastmanager 进行注册和注销

    Android Phone

    APP1     APP2 

     My Modules

我已将MyModules与安装在一部 Android 手机中的两个应用程序集成。

当我从其他 Android 手机向APP1发送消息时,它会接收到 APP1 的消息但APP1APP2同时触发通知。

我的广播服务.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>
4

2 回答 2

1

您似乎正在使用 Google Cloud Messaging 推送到设备。确保每个应用程序使用不同的 GCM 发件人 ID 或通道。

于 2015-09-13T07:41:09.660 回答
0

如果您想将广播限制为仅在意图上设置包的原始应用程序:

intent.setPackage(BuildConfig.APPLICATION_ID);

http://developer.android.com/reference/android/content/Intent.html#setPackage(java.lang.String)

于 2015-09-13T08:03:35.450 回答