Java – How to create an interaction between two Android applications

How to create an interaction between two Android applications… here is a solution to the problem.

How to create an interaction between two Android applications

I have 2 apps and their source code. When I press a button in application one, I need to background the “press” button in application 2 (START A SPECIFIC ACTION FROM IT, NOT A MAINACTIVITY). So, for example, execute the following command

send "press_button2" -> APP2

What’s the best way to do it?

Solution

This is a very general question, but you must use the implicit intent in “APP1” and read the intent action in “APP2”.
The steps will be:

  1. Define implicit intents in your APP1, such as
val sendIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(Intent.EXTRA_TEXT, "press_button2")
    type = "text/plain"
}
startActivity(sendIntent)
  1. In your app2, use the intent filter to set your list to receive the specified action in the activity of your choice:

<pre class=”lang-xml prettyprint-override”><activity android:name="ClickActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

  1. Handle incoming intents in your activity in your “APP2”, for example:
@SuppressLint("MissingSuperCall")
    override fun onCreate(savedInstanceState: Bundle?) {
        when {
            intent?. action == Intent.ACTION_SEND -> {
                if ("text/plain" == intent.type) {
                    intent.getStringExtra(Intent.EXTRA_TEXT)?. let {
                         Update UI to reflect text being shared
                        if (it == "press_button2"){
                            myButton.performClick()
                        }
                    }
                }
            }

}
    }

Note that other apps can also manage your Send Text action, so Android will present an app selector to the user and you won’t be able to seamlessly switch between the two apps.

Quote here

Related Problems and Solutions