【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>

猜你喜欢

转载自www.cnblogs.com/xjf125/p/12369736.html