短信链接唤起app
在 Android中點擊鏈接打開APP是一個很常見的需求。例如,電商為用戶發送優惠券之后經常會下發一條短信:某某優惠券已發送到您的賬戶中,點擊 xxx 鏈接即可查看!此時當用戶點擊鏈接之后會直接打開本地APP,進入相關頁面。?
功能實現:?
1.在manifest中為相應的activity添加intent-filter: <activity android:name=".TestActivity"> <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:host="mywebsite.com" android:pathPrefix="/openApp" android:scheme="http" /> </intent-filter></activity>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
2.在手機上模擬發一條短信,包含鏈接? http://mywebsite.com/openApp?,手機一般都能自動識別鏈接,點擊鏈接后系統會彈出選擇框,如下:?
點擊自己的APP(AndroidTest)之后,系統就會自動打開AndroidTest這個程序的TestActivity這個頁面。?
3.然而,上述做法顯然是不完美的,因為用戶很可能會選擇瀏覽器打開此鏈接!為了解決這個問題,可以將scheme屬性修改為自定義的,例如: <data android:host="mywebsite.com" android:pathPrefix="/openApp" android:scheme="myapp" />
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
此時,對應的鏈接地址為 myapp://mywebsite.com/openApp . 因為手機本地只有我們自己的程序能夠識別 myapp 這個協議,所以會直接打開APP。然而依舊存在問題:? (1)如果把該鏈接放在網頁上,希望希望用戶點擊鏈接后打開APP,那么上述做法是沒有問題的。例如網頁中添加如下代碼即可: <a href='myapp://mywebsite.com/openApp'>點擊打開APP</a>
- 1
- 1
(2)但是,如果把鏈接放在短信中就不行了。因為 myapp 這個協議系統的短信程序也不能識別,所以不會標記為鏈接樣式,也就是說用戶不能直接點擊。? 解決該問題的方法是使用網頁重定向功能,例如在短信中發送鏈接:? http://abc.com/openApp?,然后在該網頁上添加重定向: <meta http-equiv="Refresh" content="0;url=myapp://mywebsite.com/openApp?name=zhangsan&age=20" />
- 1
- 1
用戶在短信中點擊后會使用瀏覽器打開鏈接,然后自動打開自己的APP。? 4.最后,在TestActivity中可以獲取鏈接url傳遞的參數: Intent intent = getIntent();String action = intent.getAction();if (Intent.ACTION_VIEW.equals(action)) { Uri uri = intent.getData(); if (uri != null) { String name = uri.getQueryParameter("name"); String age = uri.getQueryParameter("age"); Toast.makeText(this, "name=" + name + ",age=" + age, Toast.LENGTH_SHORT).show(); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
本篇完,歡迎討論。
自己很喜歡的一片文章,轉載過來希望能幫助到更多同學!
總結
- 上一篇: 麦凯隆全屋分质供水 保障家庭饮用水安全与
- 下一篇: 小写金额转为中文大写