Android中Scheme跳轉協議
阿新 • • 發佈:2019-01-23
Android中Activity之間的跳轉我們可以直接使用顯示或者隱式意圖跳轉都可以
但是實際開發過程中可能會碰到這類問題
比如App做活動,通過推送過來的訊息告訴客戶端跳轉到某某介面,客戶端本地自然不能寫死,不然就麻煩了
今天小結一下開發過程中碰到的這類問題的解決方式:
我們都知道網站都是通過URL的形式訪問的
同樣的我們App也完全可以通過這種方式進行跳轉
舉個小例子
<a href='andy://domain/path?params'>點我試試</a>
andy為自定義的scheme,固定字串。
在清單檔案中加入IntentFilter
在TextView中顯示
當然這裡設定了當前的Activity的啟動模式為singleTask,防止MainActivity重複啟動
然後在MainActivtiy中重寫onNewIntent方法,獲取引數
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null) {
System.out.println(uri.toString());
}
}
斷點可以看到已經有資料傳遞過來了
這個時候我們只需要根據Uri獲取裡面的引數然後做相應的動作即可
Uri結構的基本形式
[scheme:][//domain][path][?query][#fragment]
現在我們定義具體的引數
比如我們跳轉的頁面是SchemeActivtiy引數buffer
domain=scheme_activity
buffer=這是個字串
<a href='andy://scheme_activity?type=0&buffer=這是個字串'>點我一下</a>
private static final String SCHEME_DOMAIN = "scheme_activity";
private static final String TAG = MainActivity.class.getSimpleName();
相關解析程式碼
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null) {
dispatchUri(uri);
} else {
Log.e(TAG, "Uri is null");
}
}
private void dispatchUri(Uri uri) {
try {
final String domain = uri.getAuthority();
if (TextUtils.equals(SCHEME_DOMAIN, domain)) {
final String buffer = uri.getQueryParameter("buffer");
final int type = Integer.valueOf(uri.getQueryParameter("type"));
Toast.makeText(this, type + " " + buffer, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(TAG, "Uri Parse Error");
}
}
點選測試