1

I have two Android applications A1 and A2.

Both applications are started and presenting respectively an activity B1 and B2 on the screen.

Application A1 is in foreground. Application A2 is in background.

Both are using the device's barcode reader. Activities B1 and B2 are capable of receiving broadcast messages from the barcode reader.

The applications use the Java package android.content.BroadcastReceiver.

Here is what I do:

  • In the first application A1, I scan a barcode.
  • The barcode value is printed in a view on the screen B1 in application A1.
  • My problem is that it is also printed in a view on the screen B2 in the second application A2.

When I scanned the barcode in the application A1, it also entered the "onReceive()" method in the application A2. The second application received the broadcast messages from the first application.

My question is: how can I make the second application A2 ignore the broadcast messages from other applications?

Please ask for more details if needed.

Thanks.

Léa Massiot
  • 1,928
  • 6
  • 25
  • 43
  • 1
    Did you write A2? If so, you need to decide what your rule is. If the rule is "do not scan barcodes in the background", adjust your code to disable or unregister your receiver when you are in the background (e.g., using `ProcessLifecycleOwner`). If the rule is "do not scan barcodes while A1 is around", have A1 tell A2 what to do by some form of IPC (broadcast, service, etc.). – CommonsWare Jul 03 '20 at 17:24
  • Hi. I'm writing A2. I cannot change A1's code. – Léa Massiot Jul 03 '20 at 17:27
  • 1
    Then your rule will need to be "do not scan barcodes in the background", I guess. – CommonsWare Jul 03 '20 at 17:34
  • Very nice. Thank you. That solves my problem. I used this thread for implementation: https://stackoverflow.com/questions/56780722/how-to-catch-lifecycle-events-with-processlifecycleowner – Léa Massiot Jul 03 '20 at 18:16

1 Answers1

0

You need to decide what the trigger is for A2 to move from normal operation to a mode where it ignores broadcasts. Since you did not write A1, one possible trigger is "A2 moves to the background". For that, you can use ProcessLifecycleOwner, to find out when your entire app moves between foreground and background UI states. Then, when you are in the background, you can do something to ignore the barcode events, such as:

  • Unregister the receiver, if you registered it via registerReceiver() (which I assume is the case)

  • Disable the receiver, if you registered it in the manifest

  • Keep track of your foreground/background state in some flag, and have your receiver use that flag to decide whether to process or ignore the barcode broadcast

  • Etc.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491