简体   繁体   English

如何在两个Android应用程序之间创建交互

[英]How to create interaction between two android applications

I have 2 applications with their source codes. 我有两个源代码应用程序。 When I press button in application one, I need to background "press" button in application 2 (start specific action from it, not MainActivity). 当我在应用程序一中按下按钮时,我需要在应用程序2中按下“按下”按钮(从它开始特定操作,而不是MainActivity)。 So, for example, do command like 所以,例如,做命令就像

send "press_button2" -> APP2

What is the best way to do it? 最好的方法是什么?

That's quite a generic question but you'll have to use an implicit intent from your "APP1" and read the intent action in your "APP2". 这是一个非常通用的问题,但您必须使用“APP1”中的隐含意图并阅读“APP2”中的意图操作。 The steps will be: 步骤将是:

  1. Define the implicit intent in your APP1, something like 定义APP1中的隐含意图,例如
val sendIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(Intent.EXTRA_TEXT, "press_button2")
    type = "text/plain"
}
startActivity(sendIntent)
  1. In your APP2, set up your manifest to receive the specified action in an activity of your choice, using an intent filter: 在APP2中,使用intent过滤器设置清单以在您选择的活动中接收指定的操作:
<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. In your "APP2" handle the incoming intent in your activity, something like: 在您的“APP2”处理活动中的传入意图,例如:
@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()
                        }
                    }
                }
            }

        }
    }

Be aware that also other apps would be able to manage your "send text action", so android will show an app chooser to the user, you'll not be able to switch between the two apps seamlessly. 请注意,其他应用程序也可以管理您的“发送文本操作”,因此Android会向用户显示应用程序选择器,您将无法无缝切换这两个应用程序。

Reference here 参考这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM