web页面判断是否安装某app,并判断是否打开该应用

web页面判断手机里是否安转应用的原理就是:首先试着打开手机端某个app的本地协议;如果超时就转到app下载页,下载该app。

下面说说

URL scheme 概述

URL scheme 的作用

客户端应用可以向操作系统注册一个 URL scheme,该 scheme 用于从浏览器或其他应用中启动本应用。通过指定的 URL 字段,可以让应用在被调起后直接打开某些特定页面,比如车辆详情页、订单详情页、消息通知页、促销广告页等等。也可以执行某些指定动作,如订单支付等。也可以在应用内通过 html 页来直接调用显示 app 内的某个页面。

URL scheme 的格式

客户端自定义的 URL 作为从一个应用调用另一个的基础,遵循 RFC 1808 (Relative Uniform Resource Locators) 标准。这跟我们常见的网页内容 URL 格式一样。

一个普通的 URL 分为几个部分,schemehostrelativePathquery

比如:http://www.baidu.com/s?rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709,这个URL中,scheme 为 httphost 为www.baidu.comrelativePath 为 /squery 为 rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709

一个应用中使用的 URL 例子(该 URL 会调起车辆详情页):uumobile://mobile/carDetail?car_id=123456,其中 scheme 为 uumobilehost 为mobilerelativePath 为 /carDetailquery 为 car_id=123456

Scheme定义Activity

1)在androidmanifest.xml中定义scheme

<!-- 启动页 -->
<activity
    android:name="com.qiyuan.congmingtou.activity.SplashActivity"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

    </intent-filter>
    <!-- 要想在别的App上能成功调起App,必须添加intent过滤器 -->
    <intent-filter>
        <!-- 协议部分,随便设置 -->
        <data android:scheme="cmt" android:host="splash"/>
        <!-- 下面这几行也必须得设置 -->
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <action android:name="android.intent.action.VIEW" />
    </intent-filter>
</activity>
这样我们便定义了能够接受scheme请求的activity实例,当网页或者是android代码发送这种规则scheme的请求的时候就能够吊起SplashActivity了。

2.网页中Html代码和js代码

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black"/>

        <title>this's a demo</title>
        <meta id="viewport" name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,minimal-ui">
    </head>
    <body>
        <div>
            <a id="J-call-app" href="javascript:;" class="label">立即打开&gt;&gt;</a>
            <input id="J-download-app" type="hidden" name="storeurl" value="http://m.chanyouji.cn/apk/chanyouji-2.2.0.apk">
        </div>

        <script>
            (function(){
                var ua = navigator.userAgent.toLowerCase();
                var t;
                var config = {
                    /*scheme:必须*/
                    scheme_IOS: 'IfInstalledCongMingTou://congmingtou',
                    scheme_Adr: 'cmt://splash',
                    download_url: document.getElementById('J-download-app').value,
                    timeout: 600
                };

                function openclient() {
                    var startTime = Date.now();

                    var ifr = document.createElement('iframe');


                    ifr.src = ua.indexOf('os') > 0 ? config.scheme_IOS : config.scheme_Adr;
                    ifr.style.display = 'none';
                    document.body.appendChild(ifr);

                    var t = setTimeout(function() {
                        var endTime = Date.now();

                        if (!startTime || endTime - startTime < config.timeout + 200) {
                            window.location = config.download_url;
                        } else {
                            
                        }
                    }, config.timeout);

                    window.onblur = function() {
                        clearTimeout(t);
                    }
                }
                window.addEventListener("DOMContentLoaded", function(){
                    document.getElementById("J-call-app").addEventListener('click',openclient,false);

                }, false);
            })()
        </script>
    </body>
</html>
  如果我们要用于实现对scheme的解析,然后做出相应的动作,比如请求scheme跳转登录页面,要在SplashActivity中做写相应的代码:

public class SplashActivity extends Activity{
    public Activity mContext = null;

    public void onCreate(Bundle b)
    {
        super.onCreate(b);
        mContext = this;
        Uri uri = getIntent().getData();
        if (uri != null)
        {
            List<String> pathSegments = uri.getPathSegments();
            String uriQuery = uri.getQuery();
            Intent intent            if (pathSegments != null && pathSegments.size() > 0) {
                // 解析SCHEME
                if (someif) {
                    dosomething();
                }
                else {
                    // 若解析不到SCHEME,则关闭NativeAppActivity                    finish();
                }
            } else {
                finish();
            }
        } else {
            finish();
        }
    }

}

这里简单说一下,我们可以通过Intent对象获取调用的scheme的host等信息

this.getIntent().getScheme();//获得Scheme名称  
this.getIntent().getDataString();//获得Uri全部路径 

 
 

通过服务器下发跳转路径跳转相应页面

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("uumobile://yongche/123123123")));

 
 

这里的”uumobile://yongche/123123123”就是服务器下发的跳转路径,当我们执行startActivity的时候就会调起SpalshActivity,然后我们通过在SpalshActivity解析scheme的内容,跳转相应的页面



总结: 
android中的scheme是一种非常好的实现机制,通过定义自己的scheme协议,可以非常方便跳转app中的各个页面; 
通过scheme协议,服务器可以定制化告诉App跳转那个页面,可以通过通知栏消息定制化跳转页面,可以通过H5页面跳转页面等。





### 回答1: 使用Android Studio中的nanohttpd库创建HTTP服务器,并使用WebView打开HTML页面的步骤如下: 1. 首先,在build.gradle文件中的dependencies块中添加依赖项: ``` implementation 'org.nanohttpd:nanohttpd-webserver:2.3.1' ``` 2. 在需要创建HTTP服务器的Activity中,创建一个继承自NanoHTTPD的子类。例如: ```java public class MyServer extends NanoHTTPD { public MyServer() { super(8080); // 设置服务器端口为8080 } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); // 获取请求的URI // 判断请求的URI是否为根目录,如果是,则返回HTML页面,否则返回404错误 if (uri.equals("/")) { try { InputStream inputStream = getAssets().open("index.html"); // 打开assets文件夹中的index.html文件 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); inputStream.close(); String html = builder.toString(); return newFixedLengthResponse(Response.Status.OK, "text/html", html); // 返回HTML页面 } catch (IOException e) { e.printStackTrace(); } } return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found"); // 返回404错误 } } ``` 3. 在Activity中启动HTTP服务器,并使用WebView打开页面: ```java WebView webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); // 允许WebView执行JavaScript代码 MyServer server = new MyServer(); try { server.start(); // 启动HTTP服务器 } catch (IOException e) { e.printStackTrace(); } webView.loadUrl("http://localhost:8080/"); // 使用WebView打开服务器的根目录页面 ``` 以上就是使用NanoHTTPD创建HTTP服务器并使用WebView打开HTML页面的过程。在实际开发中,可以根据需要进行相应的修改和扩展。 ### 回答2: 要使用Android Studio创建一个HTTP服务器并打开HTML页面,可以使用NanoHTTPD库来实现。 首先,需要在项目的`build.gradle`文件中添加NanoHTTPD的依赖项。在`dependencies`部分添加以下代码: ``` implementation 'org.nanohttpd:nanohttpd:2.3.1' ``` 接下来,在你的Activity或Fragment中创建一个NanoHTTPD的子类,例如`MyServer`。这个子类需要实现`NanoHTTPD.IHTTPD`接口,并重写`serve()`方法来响应HTTP请求。在这个方法中,你可以通过判断请求URI来确定要返回给客户端的内容。 具体代码如下: ```java import android.content.Context; import android.webkit.WebView; import android.widget.Toast; import org.nanohttpd.protocols.http.IHTTPSession; import org.nanohttpd.protocols.http.NanoHTTPD; import org.nanohttpd.protocols.http.response.Response; import org.nanohttpd.protocols.http.response.Status; import java.io.IOException; public class MyServer extends NanoHTTPD { private Context context; public MyServer(Context context) { super(8080); this.context = context; } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/index.html")) { String html = "<html><body><h1>Hello, World!</h1></body></html>"; return newFixedLengthResponse(Response.Status.OK, "text/html", html); } else { return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found"); } } } ``` 然后,在你的Activity或Fragment中,可以通过创建一个WebView来加载HTML页面,并启动NanoHTTPD服务器。具体代码如下: ```java import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private WebView webView; private MyServer server; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); server = new MyServer(this); try { server.start(); Toast.makeText(this, "Server started", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } webView.loadUrl("http://localhost:8080/index.html"); } @Override protected void onDestroy() { super.onDestroy(); if (server != null) { server.stop(); } } } ``` 在XML布局文件中添加一个WebView用于显示HTML页面。 这样,当你运行这个应用时,会在Android设备上启动一个HTTP服务器,并使用WebView加载服务器上的HTML页面。 ### 回答3: 使用Android Studio创建HTTP服务器并在WebView中打开HTML页面需要以下步骤: 1. 首先,将nanohttpd库导入到Android Studio项目中。可以通过在项目的build.gradle文件中添加以下行来实现: ```groovy dependencies { implementation 'org.nanohttpd:nanohttpd:2.3.1' } ``` 2. 创建一个新的Java类,继承自`NanoHTTPD`类,用于实现HTTP服务器。在这个类中,需要重写NanoHTTPD的`serve()`方法,来处理HTTP请求和响应。通过使用`InputStream`读取HTML文件的内容,并将其响应给请求的客户端。 ```java public class MyHTTPServer extends NanoHTTPD { // 构造方法 public MyHTTPServer() { super(8080); } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/")) { uri = "/index.html"; } try { InputStream inputStream = getApplicationContext().getAssets().open(uri.substring(1)); String mimeType = "text/html"; return newChunkedResponse(Response.Status.OK, mimeType, inputStream); } catch (IOException e) { e.printStackTrace(); return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "File not found"); } } } ``` 3. 在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 4. 在Activity的`onCreate()`方法中启动HTTP服务器并加载WebView: ```java public class MainActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 启动HTTP服务器 MyHTTPServer server = new MyHTTPServer(); try { server.start(); } catch (IOException e) { e.printStackTrace(); } webView = findViewById(R.id.webView); // 允许WebView执行JavaScript代码 webView.getSettings().setJavaScriptEnabled(true); // 加载HTTP服务器的地址 webView.loadUrl("http://localhost:8080"); } } ``` 以上是在Android Studio中使用NanoHTTPD库创建HTTP服务器并在WebView中打开HTML页面的步骤。可以根据需要对服务器和WebView进行进一步的自定义和配置。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值