1. 程式人生 > >藍芽列印和網口列印的實現

藍芽列印和網口列印的實現

藍芽列印的js
export default {
    install(Vue,options)
    {
        // 藍芽搜尋方法
        Vue.prototype.SearchBluetooth = function () {

            /*plus變數定義*/
            var main, BluetoothAdapter, BAdapter, IntentFilter, BluetoothDevice, receiver;

            /*其他定義*/
            var isSearchDevices = false
, //是否處於搜尋狀態 debug = false; //除錯模式 main = plus.android.runtimeMainActivity(), BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), IntentFilter = plus.android.importClass('android.content.IntentFilter'), BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice"
), BAdapter = new BluetoothAdapter.getDefaultAdapter(); return { // 檢查藍芽是否開啟 CheckBluetoothState:function(){ return BAdapter.isEnabled(); }, // 開啟藍芽 StartBluetooth:function(CallBack)
{
var self = this; if(!BAdapter.isEnabled()) { // isEnabled判斷藍芽狀態 plus.nativeUI.confirm("藍芽處於關閉狀態,是否開啟?", function(e) { if(e.index == 0) { var enable = BAdapter.enable(); // 請求開啟藍芽 console.log(enable); CallBack(true); }else{ CallBack(false); } }); } }, // 開始搜尋裝置 StartSeatch:function(CallBack,errcallback){ try { var self = this; isSearchDevices = true; var filter = new IntentFilter(), bdevice = new BluetoothDevice(); BAdapter.startDiscovery(); //開啟搜尋 receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', { onReceive: onReceiveFn }); filter.addAction(bdevice.ACTION_FOUND); filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BAdapter.ACTION_STATE_CHANGED); main.registerReceiver(receiver, filter); //註冊監聽事件 //監聽回撥函式 回撥函式會在搜尋期間 持續呼叫 function onReceiveFn(context, intent) { plus.android.importClass(intent); //通過intent例項引入intent類,方便以後的‘.’操作 //開始搜尋改變狀態 intent.getAction() === "android.bluetooth.device.action.FOUND" && (isSearchDevices = true); //判斷是否搜尋結束 if(intent.getAction() === 'android.bluetooth.adapter.action.DISCOVERY_FINISHED') { main.unregisterReceiver(receiver); //取消監聽 isSearchDevices = false; errcallback(); return; } var BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE), // 裝置物件 bleName = BleDevice.getName(), //裝置名稱 bleId = BleDevice.getAddress(); //裝置mac地址 console.dir(JSON.stringify(BleDevice)); if(!bleName || !bleId) { CallBack(false); } //判斷是否配對 if(BleDevice.getBondState() === bdevice.BOND_BONDED) { // 已配對的藍芽裝置 CallBack({ BleDevice:BleDevice, bleName:bleName, // 裝置名稱 bleId:bleId, // 裝置id isPaired:true, is_active:false }); } else { // 未配對的藍芽裝置 CallBack({ BleDevice:BleDevice, bleName:bleName, // 裝置名稱 bleId:bleId, // 裝置id isPaired:false }); } } } catch(err) { errcallback(); } }, // 配對藍芽裝置 Bluepairing:function(BleDevice,bleId,CallBack,ErrCallBack){ try { var self = this, bdevice = new BluetoothDevice(), // new java android.bluetooth.BluetoothDevice物件 BleDeviceItem = BleDevice; // 賦值裝置 if(BleDeviceItem.getAddress() === bleId){ BleDeviceItem.createBond(); // 裝置進行配對 var timeout = setInterval(function(){ // 建立定時器輪詢配對結果 if(BleDeviceItem.getBondState() === bdevice.BOND_BONDED) { // 配對成功 window.clearInterval(timeout); CallBack({ status:true, errmsg:'配對成功' }); } else if(BleDeviceItem.getBondState() === bdevice.BOND_NONE) { // 配對失敗 window.clearInterval(timeout); ErrCallBack({ status:false, errmsg:'配對失敗,請嘗試重新配對' }); } },1000); }else{ ErrCallBack({ status:false, errmsg:'裝置有誤' }); } } catch(err) { ErrCallBack({ status:false, errmsg:'異常錯誤' }); } }, CancelSearch:function(){ // 取消搜尋 main.unregisterReceiver(receiver); //取消監聽 }, } }; // 印表機連線方法 Vue.prototype.ConnectPrinter = { // 首次new這個類會建立進行連線 BluePrinter:function(bleId){ // 藍芽印表機連線 var plusMain = plus.android.runtimeMainActivity(), BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"), UUID = plus.android.importClass("java.util.UUID"), uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), BAdapter = BluetoothAdapter.getDefaultAdapter(), device = BAdapter.getRemoteDevice(bleId); plus.android.importClass(device); var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); plus.android.importClass(bluetoothSocket); if(!bluetoothSocket.isConnected()) { try { bluetoothSocket.connect(); } catch (e) { console.log(e); } } // 判斷是否連線 沒有連線則連線 this.Print = function(byteStr){ // 列印的方法 var outputStream = bluetoothSocket.getOutputStream(); plus.android.importClass(outputStream); var bytes = plus.android.invoke(byteStr, 'getBytes', 'gbk'); try { outputStream.write(bytes); } catch (e) { mui.toast('列印失敗!'); } outputStream.flush(); device = null; // bluetoothSocket.close(); console.log(2); }; // 檢查是否連線 this.ConnectStatus = function(){ return bluetoothSocket.isConnected(); }; // 關閉連線 this.CloseConnect = function(){ bluetoothSocket.close(); }; // 連線方法 this.ConnectDevice = function(){ try{ bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); bluetoothSocket.connect(); } catch(err){ console.log(err.message); return false; } }; // 儲存當前連線的bleId 用於判斷使用單例模式 this.BleId = bleId; } }; } }
網口列印的js
export default {
    sockets:false,
    connectstatus:false,
    printIns:'',
    socketconnect:function(ip,port)
    {
      try{
            if(plus.os.name=='Android')
            {
                var res = this.androidconnect(ip,port);
                return res;
            }

            if(plus.os.name == 'iOS')
            {

            }


      }catch(e){

        mui.toast("連線錯誤");
        return false;
      }
    },
    print:function(datastr,mm)
    {
        this.printIns.println(datastr);
        this.sockets.close();
    },
    androidconnect:function(ip,port)
    {
        if(this.sockets)
        {
            if(this.sockets.isConnected() && !this.sockets.isClosed()){

            }else{
                var res = this.connectsockte(ip,port);
                return res;
            }

        }else{


            var res = this.connectsockte(ip,port);
            return res;

        }
    },
    connectsockte(ip,port)
    {
        try{
                var Socket = plus.android.importClass("java.net.Socket");
                var PrintWriter = plus.android.importClass("java.io.PrintWriter");
                var BufferedWriter = plus.android.importClass("java.io.BufferedWriter");
                var OutputStreamWriter = plus.android.importClass("java.io.OutputStreamWriter");
                var BufferedReader = plus.android.importClass("java.io.BufferedReader");
                var InputStreamReader = plus.android.importClass("java.io.InputStreamReader");
                var SocketAddress = plus.android.importClass("java.net.InetSocketAddress");
                //測試改良
                var StrictMode = plus.android.importClass("android.os.StrictMode");
                var Build = plus.android.importClass("android.os.Build");
                if (Build.VERSION.SDK_INT > 9) {
                    var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                }


                var socket = new Socket();
                var socketAddr = new SocketAddress(ip,port);
                socket.connect(socketAddr,2000);
                var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(),'gbk');
                var bufferWriter = new BufferedWriter(outputStreamWriter);
                var out = new PrintWriter(bufferWriter, true);

                this.sockets = socket;
                this.printIns = out;



                mui.toast("連線成功");

                return true;
            }catch(e){

                mui.toast("連線印表機失敗");
                return false;
            }


    },
    socketclose:function()
    {
        this.sockets.close();

    }
}
具體domo地址