如果已安装就打开该Android应用,否则跳转到Google Play(不使用JavaScript)
我想在我的Android应用中添加一个按钮,让它像一个指向另一个应用的链接。若用户已经下载了该应用,直接启动;否则会打开Google Play商店并显示该应用的页面。我可以访问这两个应用,想知道在不使用服务器端JavaScript重定向的情况下,如何实现。
解决方案
如果已安装则打开Android应用,否则跳转到Google Play商店
目标应用的必需步骤:
- 为深层链接添加Intent过滤器:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="example.com" />
</intent-filter>
- 在导航图或MainActivity中处理深层链接
- 在服务器上配置
.well-known/assetlinks.json文件(请参阅文档https://developer.android.com/training/app-links/configure-assetlinks)。
需要按钮的设备的要求:
- 使用一个函数打开应用,并回退到Google Play商店:
fun openApp(context: Context) {
val url = "https://example.com/" // your deep link
val packageName = "com.app.example" // target app package name
val intent = Intent(Intent.ACTION_VIEW, url.toUri()).apply {
setPackage(packageName) // Only this app can handle the intent
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
try {
context.startActivity(intent)
} catch (e: ActivityNotFoundException) {
// Google Play Store fallback
val playIntent = Intent(
Intent.ACTION_VIEW,
"https://play.google.com/store/apps/details?id=$packageName".toUri()
)
context.startActivity(playIntent)
}
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。