I have been struggling on how what would be the best approach for inter-app communication without foregrounding each app. I thought about using BroadcastReceivers to communicate between the two apps, but it appears that they must be registered in the manifest, making it difficult to bring the data to the activities. An example would be that one app would send its status to another indicating that it is ready to start running a session. However, I would like to keep the other app in the background while I start the session and let the user switch between apps if he or she chooses.
Does anyone know what would be the best approach? Basically, I would like to send data to the other app as long as the other app is running.
I guess your thought about a broadcastreceiver
isn't too bad at all:
You don't have to register a broadcastreceiver
in the manifest, you can also have them created onDemand or even on composition with your Activity
.
But besides that there are some ways to solve your problem:
Approach #1
First of all you could use a an IntentService
and a PendingIntent
to have a simple communication using a ResultReceiver
.
See also this great stackoverflow question for more information:
android communication between two applications
Approach #2
A more universal approach could be to use a IntentFilter
and a scheme to catch send data. It's also Intent based and could be a solution for your scenario, if (!) you handle the catching of the data right: in your case only if it's running.
See also this article for a (somewhat) short example of this approach:
https://android-developers.googleblog.com/2009/11/integrating-application-with-intents.html .
Approach #3
And last but not least: make use of shared (but secured!) files and other data storage options. This could be an encrypted file and an active listener while your 2nd app is running. This would maybe also require other parts of the other mentioned options, like a running IntentService
that could be managed by an Alarmmanager
or JobScheduler
.
For such scenarios I'd recommend the official Android docs:
https://developer.android.com/training/secure-file-sharing/setup-sharing.html https://developer.android.com/guide/topics/data/data-storage.html .
Plus: since in most cases you'd have some sort of "background running service", I'd recommend you taking a look at some approaches Android gives you, since they could totally change the approach and possibilities that could fit:
https://www.bignerdranch.com/blog/choosing-the-right-background-scheduler-in-android/
Long story short:
Good luck and keep me posted! ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With