【React Native】在网页中打开Android应用程序

  React Native官方提供Linking库用于调起其他app或者本机应用。Linking的主要属性和方法有:

 属性与方法 

  canOpenURL(url); 判断设备上是否有已经安装相应应用或可以处理URL的程序,本方法会返回一个Promise对象,只有一个回调参数,格式为Boolean值。
  openURL(url); 打开设备上的某个应用或可以处理URL的程序,本方法会返回一个Promise对象。
  addEventListener(type, handler); 添加一个监听 Linking 变化的事件。type 参数应填'url',并提供一个处理函数。
  removeEventListener(type, handler); 删除一个事件处理函数。type 参数应填'url'。
  getInitialURL(); 如果应用是被一个链接调起的,则会返回相应的链接地址。否则它会返回null。

 使用

复制代码
// 在调起其他app或者本机应用前先检查是否已经安装:
Linking.canOpenURL('weixin://').then(supported => {
  if (!supported) {
    console.log('无法处理该URL:' + url);
  } else {
    return Linking.openURL('weixin://');
  }
}).catch(err => console.error('错误:', err));
 
// 本应用被其注册过的外部url调起
Linking.getInitialURL().then(url => {
   if (url) {
       console.log('本app被其它应用调起:' + url);
   }
}).catch(err => {
   console.warn('错误:', err);
});
   
// 监听Linking的相关事件
Linking.addEventListener('url', this._handleOpenURL);
 
// 移除Linking的相关事件
Linking.removeEventListener('url', this._handleOpenURL);
 
_handleOpenURL(event) {
   console.log(event.url);
复制代码

 android自定义URL Scheme:

  android/app/src/main/AndroidManifest.xml文件,配置如下:

复制代码
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.auth">
    ...
 
    <application
      ...
      android:launchMode="singleTask"  // 新增1
      ...
      <activity
        ...
        // 新增2
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="auth" />
        </intent-filter>
      </activity>
      ...
    </application>
 
</manifest>
复制代码

 

posted @   Mr·Xu  阅读(607)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示