Android模仿支付宝网页启动APP或下载

    最近在做项目中需要实现网页启动手机中的客户端,如果手机中未装客户端则提示用户下载。这个技术关键点是用到了scheme,结合参考支付宝的实现方式,方法如下:

一、网页中相关代码如下:

<html>

    <head>

        <script>

            function open(){

                window.location='abc://192.168.0.14:8080/test/app/test.apk';

            }

        </script>

    </head>


    <body onload="open()">

        <a href="http://192.168.0.14:8080/test/app/test.apk">下载</a>

    </body>

</html>


二、Android中的AndroidManifest.xml要启动的Activity添加如下代码:

<intent-filter>

    <action android:name="android.intent.action.VIEW"/> 

    <category android:name="android.intent.category.BROWSABLE"/> 

    <category android:name="android.intent.category.DEFAULT"/> 

    <data 

        android:scheme="abc"

        android:host="192.168.0.14" /> 

</intent-filter>


插个曲:上面网页中命名的abc与AndroidManifest.xml中的abc必须要一致,当然了,可以改成你喜欢的名称。其次,如果你不想精准匹配的话,AndroidManifest.xml中的<data/>中只需要android:scheme="abc"就行了;如果想精确匹配,那么你就需要写更详细一点,比如:android:host、android:port、android:path。


    以上就实现了模仿支付宝的网页启动与下载功能,大家可以尝试一下。有一点要注意,scheme不能是http,浏览器遇到http时,是不会发intent给外界了。具体原理大家就百度一下吧,我这里就不说了,说的不好反而误导你们了,呵呵。


    除了上面模仿支付宝的方法外,还有一种方法,就是通过控件WebView来实现,当然了只有自己的应用中的WebView才会实现我们想要的功能,因为要加代码稍作改动的,别人的应用应该不会帮你去实现吧?

    在自己的应用中使用WebView来实现的话,会更加完美,可以做到用仅用一个下载按钮来实现启动或下载(若手机中安装了应用,点击下载就会直接启动应用,而不是去下载应用;若手机中没有安装应用,则点击下载就会真的去下载应用了)。实现方法是在WebView中设置自定义的WebViewClient,重写shouldOverrideUrlLoading (WebView view, String url) ,监测url是否符合约定,如符合约定,则启动客户端,求例代码如下:

if(url.contains("abc"))

{

    try

    {

        Uri uri = Uri.parse("abc://192.168.0.14:8080/test/app/test.apk");

        Intent intent = new Intent(Intent.ACTION_VIEW, uri);

        startActivity(intent);

    }

    catch(Exception e)

    {

        //启动失败

        StringBuffer sb = new StringBuffer(url);

        sb.replace(0, 11, "http");

 

        Uri uri = Uri.parse(sb.toString()); 

        Intent intent = new Intent(Intent.ACTION_VIEW, uri); 

        startActivity(intent);

             

        return true;

    }

}


相信大家都能看懂吧?再不懂就留言吧!