在开发过程中,经常会遇到两个app之间跳转、或者浏览器链接跳转app的需求,这里简单总结一下。

1.简单的从一个app跳转到另一个app

直接用intent就可以实现。
只要知道目标activity的包名和类名就可以直接跳转了。

/**
     * 方法1:intent的显式跳转
     */
    private fun jumpDemo2() {
        val intent = Intent()
        intent.component = ComponentName("com.example.demo2", "com.example.demo2.MainActivity")
        startActivity(intent)
    }

2.deepLink方式跳转

这种方式应用场景更广可以在浏览器或者网页中通过链接跳转到目标app并传递数据。
具体实现步骤如下:

  1. 配置目标activity的intent-filter
    配置activity中的host,scheme,pathPrefix。代码如下:
<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- deepLink 配置项-->
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />

                <data
                    android:host="com.example.demo2"
                    android:pathPrefix="/open"
                    android:scheme="deeplink" />
            </intent-filter>

        </activity>
  1. 生成link链接
    规则:{scheme}://{host}{pathPrefix}
    link: deeplink://com.example.demo2/open
    如果想传递参数的话用&连接
    deeplink://com.example.demo2/open?name=yao&age=20
    把拼接好的链接直接在跳转的地方用就ok,
    例如在h5中
<html>
<head>
    <meta name="meta_name" content="helloworld">
</head>
<body>
<a href="deeplink://com.example.demo2/open?name=yao&age=20">启动demo</a>
</body>
</html>
  1. 在目标activity中直接获取传递的数据即可
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        showMsg()
    }

    private fun showMsg() {
        intent.data?.run {
            tv_msg.text = "this is from demo1 data: " +
                    "\n host=${host}, \n scheme=${scheme}, " +
                    "\n params=${pathSegments}" +
                    "\n data:${this.toString().substring(this.toString().indexOf("?") + 1)}"
        }
    }
}

这样就实现了应用间跳转的问题。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐