安卓和rn喚起其餘app應用

對於app來講,不少時候都須要在本app中喚起其餘app應用,本文簡單的列舉了安卓和react-native對於喚起其餘app的一些作法。html

安卓

1)url scheme喚起

  • 使用場景:react

    1. h5頁面跳轉到app;
    2. 一個app跳轉到另外一個app;
    3. app內的跳轉;
  • 具體形式:

安卓的url喚起實際上是採用了url scheme方式喚起,該方式和日常的url的結構基本一致;android

scheme://host:port/pathname?querystring; 
// 注意這裏的scheme不是http護着https; 
// demo: 
test//baidu.com:9001/a/b?a1=1&a2=2
  • 調用方式:假設A應用調用B應用;

在B應用的AndroidManifest.xml文件中定義相關配置:
image.pngweb

B應用獲取跳轉過來的參數:react-native

Intent intent = getIntent();
String action = intent.getAction(); 
String scheme = intent.getScheme(); 
Set categories = intent.getCategories(); 
Uri data = intent.getData(); 
data.getHost(); 
data.getPath(); 
data.getPort();

A應用若是是網頁:api

<a href='test://baidu.com:9001/a/b?...'>xxx</a>
window.location = "test://baidu.com:9001/a/b?...";

A是一個app應用:
首先要知道B應用的url scheme的叫什麼,而後再調用startActivity喚起;promise

Uri uri = Uri.parse("test://baidu.com:9001/a/b?a1=1&a2=2"); 
Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(intent);

優勢:不暴露包命;
缺點:host path schemeA應用和B應用得規定死;app

2)ComponentName喚起:

  • 做用:就是用來定義一個應用程序組件,目的就是爲了讓app之間進行互相跳轉;
  • 用法:

step1:建立一個應用類組件--- new ComponentName(string pkg, string classname);其中
pkg:就是AndroidManifest.xml中manifest組件定義的package的包名;
classname:就是xml文件中activity組件定義的android:name的類名;url

step2:建立一個意圖Intent,而後添加組件到意圖中;spa

Intent intent = new Intent() 
intent.setComponent(intent)

step3:最後一步就是啓動另外一個應用 ---- startActivity(intent)

  • demo:
Intent intent = new Intent(Intent.ACTION\_MAIN); 
/**知道要跳轉應用的包命與目標Activity**/ 
ComponentName componentName = new ComponentName("kuyu.com.xxxx", "kuyu.com.xxxx.xxx.login.WelcomeActivity"); 
intent.setComponent(componentName); 
intent.putExtra("", ""); //這裏Intent傳值 
startActivity(intent);

RN

rn能夠經過Linking這個組件來喚起其餘app應用(前提要知道對應app應用的url scheme),他主要提供了三個主要的api調用:

1.canOpenURL(url):判斷當前url scheme是否在安卓機器上有安裝過;

Linking.canOpenURL('weixin://') 
    .then(isSupport => { ... })
    .catch(e => {...})

2.openURL(url):在安卓上打開指定的url scheme的app應用;

Linking.canOpenURL('weixin://')
       .then(isSupport => { 
           if (isSupport) { 
             return Linking.openURL('weixin://');
           } else { ... }
        }).catch(e => {...})

注意:本方法會返回一個Promise對象。若是用戶在彈出的對話框中點擊了確認或是 url 自動打開了,則 promise 成功完成。若是用戶在彈出的對話框中點擊取消或是沒有對應應用能夠處理此類型的 url,則 promise 會失敗。

3.getInitialURL():若是本應用被另外一個應用調用時,會返回相應的鏈接地址;

genInitialURL().then(url => {...}).catch(e => {...});

web site:
使用Linking喚醒其它app及WebView
Intent屬性詳解一 component屬性
帶你瞭解Android的Scheme協議

相關文章
相關標籤/搜索