hbuilder离线打包 websocket全局共享

来源:互联网 发布:批处理编程 pdf 编辑:程序博客网 时间:2024/05/29 16:04

离线打包后手写websocket

用到的jar包  android-support-v4.jar 


package com.websocket;

import java.io.IOException;
import java.util.ArrayList;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.WebSocket;
import android.R.plurals;
import android.content.Context;
import android.util.Log;
import android.webkit.WebView;
import com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback;
import io.dcloud.WebAppActivity;
import io.dcloud.common.DHInterface.IApp;
import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.DHInterface.StandardFeature;
import io.dcloud.common.util.JSUtil;
import io.dcloud.feature.internal.sdk.SDK;


public class HWebSocket extends StandardFeature{
private static int tryTime = 1;
private static WebSocket webSocket = null;
public static void webConnect(final String url) {

        if (webSocket == null) {
            try {
           
                AsyncHttpClient.getDefaultInstance().websocket(url, null, new WebSocketConnectCallback() {
                    @Override
                    public void onCompleted(Exception ex, WebSocket _webSocket) {
                    if(ex!=null) {
                   
                    //获取webview
                            ArrayList<IWebview> ss = SDK.obtainAllIWebview();
                            for (IWebview iWebview : ss) {
                                    iWebview.evalJS("onClosed('0')");
                            }
                            ex.printStackTrace();
                    }
                        webSocket = _webSocket;
                        webSocket.setStringCallback(new WebSocket.StringCallback() {
                            @Override
                            public void onStringAvailable(String s) {
                                Log.d("websocket",s);
                                //获取webview
                                ArrayList<IWebview> ss = SDK.obtainAllIWebview();
                                for (IWebview iWebview : ss) {
//                                    if (iWebview.getOriginalUrl().equals("messageList.html")) {
//                                 if((s.indexOf("Question")!=-1 || s.indexOf("GroupQuestion")!=-1 || s.indexOf("SingleQuestion")!=-1 || s.indexOf("DrawingBoardQuestion")!=-1) && (iWebview.getOriginalUrl()=="ClassroomInteraction/st_answer.html" || iWebview.getOriginalUrl()=="learnTast/drawingBoard.html")){
//                                 continue;
//                                 }
                               
                                WebView vs = iWebview.obtainWebview();
                                String url  = iWebview.getOriginalUrl();
                                        iWebview.evalJS("wsRecive('" + s + "')");
//                                        break;
//                                    }
                                }
                            }
                        });
                        webSocket.setClosedCallback(new CompletedCallback() {
                            @Override
                            public void onCompleted(Exception ex) {
                                try {
                                    if (ex != null)
                                        Log.e("WebSocket", "Error");
                                } finally {
                                ArrayList<IWebview> ss = SDK.obtainAllIWebview();
                               
                                for (IWebview iWebview : ss) {
//                                      if (iWebview.getOriginalUrl().equals("messageList.html")) {
                                         iWebview.evalJS("onClosed('0')");
//                                      }
                        };
                                }
                            }
                        });
                    }
                });
            }catch(Exception e){
            //socket关闭时候事件触发
            ArrayList<IWebview> ss = SDK.obtainAllIWebview();
            for (IWebview iWebview : ss) {
//                 if (iWebview.getOriginalUrl().equals("messageList.html")) {
            iWebview.evalJS("onClosed('0')");
            };
            e.printStackTrace();
            }
            finally {
//                if (tryTime <= 1) {
//                    tryTime += 1;
//                    webConnect(url);
//                }
//             ArrayList<IWebview> ss = SDK.obtainAllIWebview();
//             for (IWebview iWebview : ss) {
////                 if (iWebview.getOriginalUrl().equals("messageList.html")) {
//             iWebview.evalJS("onClosed('0')");
//             break;
//             };
            }
        } 
    }

//发送socket
public static void sendMsg(String msg) {
// show(msg);
        if (webSocket != null && webSocket.isOpen()) {
        Log.d("c", msg);
            webSocket.send(msg);
            Log.d("s",webSocket.isOpen()+"");
        }
    }


//关闭socket
public static void close() {
        if (webSocket != null && webSocket.isOpen()) {
            webSocket.close();
            webSocket = null;
        }
    }

//检查ip是否畅通
public static String  pingIpAddress(String ipAddress) {
String falg = "false";
Process process = null;  
       try {
        process = Runtime.getRuntime().exec("ping -c 1 -i 0.5 -W 1 " + ipAddress);  
           int status = process.waitFor();
           if (status == 0) {
               falg = "true";
           } else {  
               falg = "false";
           }
       } catch (IOException e) {
           e.printStackTrace();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return JSUtil.wrapJsVar(falg);
   }
 

}



js端 代码 


var WsUrl = "ws://192.168.2.167:8080";
var ip = "192.168.2.167";
var port = "8080";
if(localStorage.getItem("ip") != null && localStorage.getItem("ip") != "") {
    ip = localStorage.getItem("ip");
    WsUrl = "ws://"+ip+":"+port;
}




//var ajaxUrl = "";
// 内网ip是否畅通 畅通则打开websocket
function pingIpAddress() {
    if(localStorage.getItem("ip") != null && localStorage.getItem("ip") != "") {
        ip = localStorage.getItem("ip");
        WsUrl = "ws://"+ip+":"+port;
    }
    if(mui.os.android) {
        
        try{
            var Toolkit = plus.android.importClass("com.websocket.HWebSocket");
            if(Toolkit) {
            var t = eval(Toolkit.pingIpAddress(ip));
            if(t == 'true') {
                return true;
            } else {
                return false;
            }
            } else {
                plus.nativeUI.alert("IM服务器连接失败");
                return false;
            }
        }catch(e){
//           plus.nativeUI.alert("IM服务器连接失败");
                return false;
        }
        
    }
}


//初始化socket
function createWs() {


    if(mui.os.ios) {
        if('WebSocket' in window) {
            debug("WebSocket")
            wsClient = new WebSocket(WsUrl);
        } else if('MozWebSocket' in window) {
            debug("MozWebSocket")
            wsClient = new MozWebSocket(WsUrl);
        }
        wsClient.onopen = function() {
            onOpen()
        };
        wsClient.onclose = function() {
            onClose()
        };
        wsClient.onmessage = function(evt) {
            onMessage(evt)
        };
        wsClient.onerror = function() {
            onError()
        };
    } else if(mui.os.android) {
        var Toolkit = null;
        try{
            Toolkit = plus.android.importClass("com.websocket.HWebSocket");
            if(Toolkit) {
                //var wifiInfo = new Toolkit();
                Toolkit.webConnect(WsUrl);
                //如果可以连接则为网络为内网
                localStorage.setItem("net_flag", "true");
            } else {
                plus.nativeUI.alert("IM服务器连接失败");
            }
        }catch(e){
            localStorage.setItem("net_flag", "false");
            return false;
        }
    }
}


//发送socket
function sendMsg(msg) {


    if(mui.os.ios) {
        //缓存本地
        if(wsClient.readyState == WebSocket.OPEN) {
            wsClient.send(JSON.stringify(msg));
            _msg = null;
        } else {
            _msg = msg;
            createWs();
        }
    } else if(mui.os.android) {
        var Toolkit = null;
        try{
            Toolkit = plus.android.importClass("com.websocket.HWebSocket");
            if(Toolkit) {
                Toolkit.sendMsg(msg);
            } else {
                plus.nativeUI.alert("IM服务器连接失败");
            }
        }catch(e){
            return false;
        }
    }
}


//socket 返回值
function wsRecive(e) {

}

//   0 错误断开 1 自然断开
function onClosed(e) {
    if(e == '0') {
        var ws = plus.webview.currentWebview();


        if(ws.id=='entrance'){
            return;
        }
        var ars = plus.webview.getDisplayWebview();
        if(ars[ars.length-1].id==ws.id){
            mui.alert("连接已断开,请重启程序");
        }
        
    }
}


//关闭socket方法
var close =  function() {
    var Toolkit = null;
    try{    
        Toolkit = plus.android.importClass("com.websocket.HWebSocket");
        if(Toolkit) {
            Toolkit.close();
        } else {
            plus.nativeUI.alert("IM服务器连接失败");
        }
    }catch(e){
        return false;
    }
}


配置hbuilder 类引用

/assets/data/dcloud_properties.xml  

<feature name="HWebSocket" value="com.websocket.HWebSocket"></feature>




原创粉丝点击