G 蓝牙打印

//蓝牙
public MyPrinter myPrinter;
public static int mComFd = -1;
static CommonApi mCommonApi;
private Dialog connectBTDialog;
private BTDeviceFinder mBtDevFinder;
private ArrayAdapter<String> mBTDevListViewAdapter;
private ArrayList<String> btDevAddressList = new ArrayList<>();
private String mac;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_print_details); 


    /**--------------------蓝牙打印--------------------------*/
    myPrinter = MyPrinter.getInstance();
    createDialog();
    // 获取蓝牙设备查找类的实例
    mBtDevFinder = BTDeviceFinder.getFinder(PrintDetailsAcitivty.this);
    mBtDevFinder.setClientListener(mBtDevFoundListener);
    mBtDevFinder.checkBTAdapter();
    mBtDevFinder.openBTAdapter();

    registerBoradcastReceiver();
    send(new byte[]{0x1F, 0x1B, 0x1F, (byte) 0x80, 0x04, 0x05,
            0x06, 0x44});
    send(new byte[]{0x1b, 0x23, 0x23, 0x53, 0x54, 0x44,
            0x50, 0x27});
    send(new byte[]{0x1d, 0x61, 0x00});
    send(new byte[]{0x1D, 0x54, 0x1D, 0x28, 0x46, 0x04, 0x00,
            0x01, 0x00, 0x40, 0x00});

    initView();

    initData();


}

 

@Override
protected void onDestroy() {
    super.onDestroy();
    if (state == "开始"){
        PrintDetailsAcitivty.this.unregisterReceiver(stateChangeReceiver);//注册广播
    }
}
private void initData() { 
  
print_details22 = findViewById(R.id.print_details22);
    print_details22.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (!MyPrinter.isBuleTConnect) {
                ToastUtils.toast(PrintDetailsAcitivty.this, "请先链接蓝牙打印机");
                try {
                    if (myPrinter.btSocket != null) {
                        myPrinter.btSocket.close();
                    }
                } catch (IOException var2) {
                    var2.printStackTrace();
                }
                myPrinter.OutStream = null;
                connectBTDialog.show();
                btDevAddressList.clear();
                mBTDevListViewAdapter.clear();
                int ret = mBtDevFinder.searchtBTDevice();
                if (ret < 0) {
                    String notice = "";
                    Resources resource = getResources();
                    if (-1 == ret) {
                        notice = resource
                                .getString(R.string.NoteStrNotFounddBTAdapter);
                    } else if (-2 == ret) {
                        notice = resource
                                .getString(R.string.NoteStrOpenBTPlease);
                    }
                    mBTDevListViewAdapter.add(notice);
                }
            }else {
                GoPrintLabel();
            }
        }
    });
}

 

  /**
     * 打印内容  标签打印  小纸
     */
    String  name01 = "",name02 = "";
    private void GoPrintLabel(){
        int width = 45;
        int height = 22;
        Log.e("---服务码id:",id+"/");
        myPrinter.setup(width, height, 4, 15, 0, 2, 0, PrintDetailsAcitivty.this);
        myPrinter.clearbuffer(PrintDetailsAcitivty.this);
        String s = "TEXT " + countX(120) + "," + countY(20) + ",\"TSS24.BF2\",0,1,1,\""+ OwnCustomerName +"\n";
        myPrinter.sendcommand(str2byte(s), PrintDetailsAcitivty.this);

        String s3 = "TEXT " + countX(250) + "," + countY(60) + ",\"TSS24.BF2\",0,1,1,\"名称:\n";
        myPrinter.sendcommand(str2byte(s3), PrintDetailsAcitivty.this);
        String s4 = "TEXT " + countX(250) + "," + countY(100) + ",\"TSS24.BF2\",0,1,1,\"编号:\n";
        myPrinter.sendcommand(str2byte(s4), PrintDetailsAcitivty.this);
        String s44 = "TEXT " + countX(250) + "," + countY(150) + ",\"TSS24.BF2\",0,1,1,\"维保单位:\n";
        myPrinter.sendcommand(str2byte(s44), PrintDetailsAcitivty.this);

        String s8 = "TEXT " + countX(330) + "," + countY(60) + ",\"TSS24.BF2\",0,1,1,\""+OwnGoodsName+"\n";
        myPrinter.sendcommand(str2byte(s8), PrintDetailsAcitivty.this);

        String s9 = "TEXT " + countX(330) + "," + countY(100) + ",\"TSS24.BF2\",0,1,1,\""+SerialNumber+"\n";
        myPrinter.sendcommand(str2byte(s9), PrintDetailsAcitivty.this);

        if (OwnCustomerName.length()>4){
            name01 = OwnCustomerName.substring(0,4); // or  str=str.Remove(i,str.Length-i);
            name02 = OwnCustomerName.substring(4,OwnCustomerName.length());
            Log.e("companyName01=",name01+"/"+name02);
            String s99 = "TEXT " + countX(400) + "," + countY(150) + ",\"TSS24.BF2\",0,1,1,\""+ name01 +"\n";
            myPrinter.sendcommand(str2byte(s99), PrintDetailsAcitivty.this);
            String s10 = "TEXT " + countX(250) + "," + countY(200) + ",\"TSS24.BF2\",0,1,1,\""+ name02 +"\n";
            myPrinter.sendcommand(str2byte(s10), PrintDetailsAcitivty.this);
        }else {
            Log.e("companyName02=",OwnCustomerName);
            String s99 = "TEXT " + countX(320) + "," + countY(150) + ",\"TSS24.BF2\",0,1,1,\" \n";
            myPrinter.sendcommand(str2byte(s99), PrintDetailsAcitivty.this);
            String s10 = "TEXT " + countX(250) + "," + countY(200) + ",\"TSS24.BF2\",0,1,1,\""+ OwnCustomerName +"\n";
            myPrinter.sendcommand(str2byte(s10), PrintDetailsAcitivty.this);
        }


        //330  60  L,4,A,0,M1,S3
        String str = "QRCODE " + countX(110) + "," + countY(60) + ",L,3,A,0,M1,S3,\"" + UrlConfig.IP + "u.html?id=" + id + "\n";
        myPrinter.sendcommand(str, PrintDetailsAcitivty.this);
        Log.e("蓝牙打印str", str);
        myPrinter.barcode(165, 160, "128", 20, 0, 180, 1, 3, "9876543");

        myPrinter.printlabel(1, 1, PrintDetailsAcitivty.this);
    }
    private byte[] str2byte(String s){
        byte b[] = new byte[0];
        try {
            b = s.getBytes("GBK");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return b;
    }
    private String countX(int width){
        String s = "";
        s = Math.ceil(width*5/7) + "";
        return s;

    }
    private String countY(int height){
        String s = "";
        s = Math.ceil(height*2/3) + "";
        return s;
    }

    /** 发送数据 */
    public static void send(byte[] data) {
        if (data == null)
            return;
        if (mComFd > 0) {
            mCommonApi.writeCom(mComFd, data, data.length);
        }
    }

    /**注册监听*/
    private void registerBoradcastReceiver() {
        IntentFilter stateChangeFilter = new IntentFilter(
                BluetoothAdapter.ACTION_STATE_CHANGED);
        IntentFilter connectedFilter = new IntentFilter(
                BluetoothDevice.ACTION_ACL_CONNECTED);
        IntentFilter disConnectedFilter = new IntentFilter(
                BluetoothDevice.ACTION_ACL_DISCONNECTED);
        PrintDetailsAcitivty.this.registerReceiver(stateChangeReceiver, stateChangeFilter);
        PrintDetailsAcitivty.this.registerReceiver(stateChangeReceiver, connectedFilter);
        PrintDetailsAcitivty.this.registerReceiver(stateChangeReceiver, disConnectedFilter);
        state = "开始";
    }
    /**
     *蓝牙连接
     */
    private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
                //连接上了
                Log.d("蓝牙连接", "蓝牙连接");
            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
                //蓝牙连接被切断
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                Log.d("蓝牙连接被切断", "蓝牙连接被切断");
                ToastUtils.toast(context, "蓝牙连接断开,请重新连接!");
                myPrinter.isBuleTConnect = false;
                return;
            }
        }
    };
    /**
     * 蓝牙设备列表
     */
    public void createDialog() {
        // 创建一个对话框 并嵌入一个ListView,用来显示被发现的蓝牙设备
        ListView deviceList = new ListView(PrintDetailsAcitivty.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(PrintDetailsAcitivty.this, AlertDialog.THEME_HOLO_LIGHT);
        builder.setTitle("蓝牙设备列表");
        builder.setView(deviceList);
        connectBTDialog = builder.create();
        connectBTDialog.setOnShowListener(onDialogShow);
        mBTDevListViewAdapter = new ArrayAdapter<String>(PrintDetailsAcitivty.this, android.R.layout.simple_list_item_1);
        deviceList.setAdapter(mBTDevListViewAdapter);
        deviceList.setOnItemClickListener(onItemClick);
    }


    /**
     * 对话框中Item点击事件
     */
    private AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            String itemText = mBTDevListViewAdapter.getItem(position);
            String devinfo[] = itemText.split("\n");
            Log.e("mac1", devinfo[0]);
            Log.e("mac2", devinfo[1]);
            if (devinfo.length == 2
                    && devinfo[1]
                    .matches("^([0-9a-fA-F]{2})(([:][0-9a-fA-F]{2}){5})$")) {
                String mac = devinfo[1];
                Log.e("dfa", mac);
                Message msg = new Message();
                msg.what = 1;
                Bundle bundle = new Bundle();
                bundle.putString("mac", mac);
                msg.setData(bundle);
                uiHandler.sendMessage(msg);
            } else {
                mBtDevFinder.openBTAdapter();
            }
            connectBTDialog.dismiss();
        }
    };
    //uiHandler在主线程中创建,所以自动绑定主线程
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mac = msg.getData().getString("mac");
                    myPrinter.openport(mac, PrintDetailsAcitivty.this);
                    break;
                case 2:
                    break;
            }
        }
    };

    /**
     * 对象框显示触发事件
     */
    private DialogInterface.OnShowListener onDialogShow = new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            try {
                btDevAddressList.clear();
                mBTDevListViewAdapter.clear();
                int ret = mBtDevFinder.searchtBTDevice();
                if (ret < 0) {
                    String notice = "";
                    Resources resource = getResources();
                    if (-1 == ret) {
                        notice = resource
                                .getString(R.string.NoteStrNotFounddBTAdapter);
                    } else if (-2 == ret) {
                    } else if (-2 == ret) {
                        notice = resource
                                .getString(R.string.NoteStrOpenBTPlease);
                    }
                    mBTDevListViewAdapter.add(notice);
                }
            } catch (Exception e) {
                //PgyCrashManager.reportCaughtException(, e);
                e.printStackTrace();
            }
        }
    };

    /**
     * 蓝牙设备搜索结果返回
     */
    private BTDeviceFinder.OnDeviceFoundListener mBtDevFoundListener = new BTDeviceFinder.OnDeviceFoundListener() {

        @Override
        public void onDevieFound(BluetoothDevice device) {
            String devAddress = device.getAddress();
//            Log.e("add", devAddress);
            if (devAddress != null && !devAddress.isEmpty()) {
                if (!btDevAddressList.contains(devAddress)) {
                    btDevAddressList.add(devAddress);
                    mBTDevListViewAdapter.add(device.getName() + "\n"
                            + devAddress);
                    Log.e("add地址", device.getName() + "\n" + devAddress);
                }
            }
        }
    };

 

public class MyPrinter {

    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static BluetoothSocket btSocket = null;
    public static OutputStream OutStream = null;
    public static boolean isBuleTConnect = false;
    private static MyPrinter instance = null;
    public static synchronized MyPrinter getInstance() {

        if (instance == null)
            instance = new MyPrinter();
        return instance;
    }

    /**
     * quantity 密度
     * @param quantity
     * @param copy
     * @param context
     */
    public void printlabel(int quantity, int copy, Context context) {
        String message = "";
       // message = "PRINT " + quantity + ", " + copy + "\n";
        message = "PRINT " + quantity + ", " + copy + "\n";
        byte[] msgBuffer = message.getBytes();
        try {
            OutStream = btSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(OutStream == null){
                ToastUtils.toast(context,"连接失败,请重连...");
                return;
            }
            this.OutStream.write(msgBuffer);
        } catch (IOException var6) {
            var6.printStackTrace();
        }

    }

    public void barcode(int x, int y, String type, int height, int human_readable, int rotation, int narrow, int wide, String string) {
        String message = "";
        String barcode = "BARCODE ";
        String position = x + "," + y;
        String mode = "\"" + type + "\"";
        String height_value = "" + height;
        String human_value = "" + human_readable;
        String rota = "" + rotation;
        String narrow_value = "" + narrow;
        String wide_value = "" + wide;
        String string_value = "\"" + string + "\"";
        message = barcode + position + " ," + mode + " ," + height_value + " ," + human_value + " ," + rota + " ," + narrow_value + " ," + wide_value + " ," + string_value + "\n";
        byte[] msgBuffer = message.getBytes();

        try {
            this.OutStream.write(msgBuffer);
        } catch (IOException var22) {
            var22.printStackTrace();
        }

    }

    public void sendcommand(String message, Context context) {
        byte[] msgBuffer = message.getBytes();

        try {
            if(OutStream == null){
                ToastUtils.toast(context,"连接失败,请重连...");
                return;
            }
            this.OutStream.write(msgBuffer);
        } catch (IOException var4) {
            Log.e("THINBTCLIENT", "ON RESUME: Exception during write.", var4);
        }

    }

    public void sendcommand(byte[] message, Context context) {
        try {
            if(OutStream == null){
                ToastUtils.toast(context,"连接失败,请重连...");
                return;
            }
            this.OutStream.write(message);
        } catch (IOException var3) {
            Log.e("THINBTCLIENT", "ON RESUME: Exception during write.", var3);
        }

    }

    /**
     * 设置打印机
     * @param width     宽度
     * @param height    高度
     * @param speed     速度
     * @param density   密度
     * @param sensor    传感器
     * @param sensor_distance   传感器距离
     * @param sensor_offset     传感器偏移
     * @param context
     */
    public void setup(int width, int height, int speed, int density, int sensor, int sensor_distance, int sensor_offset, Context context) {
        String message = "";
        String size = "SIZE " + width + " mm" + ", " + height + " mm";
        String speed_value = "SPEED " + speed;
        //String density_value = "DENSITY " + density;
        String density_value = "DENSITY " + 15;
        String sensor_value = "";
        String direction ="DIRECTION "+ 1;//设置打印方向



        if(sensor == 0) {
            sensor_value = "GAP " + sensor_distance + " mm" + ", " + sensor_offset + " mm";
        } else if(sensor == 1) {
            sensor_value = "BLINE " + sensor_distance + " mm" + ", " + sensor_offset + " mm";
        }

        message = size + "\n" + speed_value + "\n" + density_value + "\n" + sensor_value + "\n" + direction + "\n";
        byte[] msgBuffer = message.getBytes();

        try {
            if(OutStream == null){
                ToastUtils.toast(context,"连接失败,请重连...");
                return;
            }
            this.OutStream.write(msgBuffer);
        } catch (IOException var15) {
            var15.printStackTrace();
        }

    }

    public void clearbuffer( Context context) {
        String message = "CLS\n";
        byte[] msgBuffer = message.getBytes();

        try {
            if(OutStream == null){
                ToastUtils.toast(context,"连接失败,请重连...");
                return;
            }
            this.OutStream.write(msgBuffer);
        } catch (IOException var4) {
            var4.printStackTrace();
        }

    }

    /**
     * string转Byte数组
     * @param s
     * @return
     */
    private byte[] str2byte(String s){
        byte b[] = new byte[0];
        try {
            b = s.getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return b;
    }

    public void openport(String address, Context context) {
        BluetoothDevice device = null;
        BluetoothAdapter mBluetoothAdapter = null;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        device = mBluetoothAdapter.getRemoteDevice(address);

        if(OutStream != null){
            ToastUtils.toast(context,"连接成功");
            return;
        }

        try {
            this.btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException var8) {
            isBuleTConnect = false;
            ToastUtils.toast(context,"连接失败1");
            return;
        }

        mBluetoothAdapter.cancelDiscovery();

        try {
            this.btSocket.connect();
            this.OutStream = this.btSocket.getOutputStream();
            if(OutStream == null){
                isBuleTConnect = false;
                ToastUtils.toast(context,"连接失败2");
                return;
            }
            isBuleTConnect = true;
            ToastUtils.toast(context,"连接成功");
        } catch (IOException var7) {
            isBuleTConnect = false;
            ToastUtils.toast(context,"连接失败3");
            try {
                this.btSocket.close();
            } catch (IOException var6) {
                isBuleTConnect = false;
                ToastUtils.toast(context,"连接失败4");
                return;
            }

        }

    }

    public void distroy(){
        isBuleTConnect = false;
        OutStream = null;
        try {
            if(btSocket!=null){
                this.btSocket.close();
            }

        } catch (IOException var2) {
            var2.printStackTrace();
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值