Android之蓝牙连接打印机

一:效果图

二:实现步骤:

1.封装了一个工具类,用于调取相应的方法、

package net.XPrinter.Example4bluetooth;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class PrintUtils {

    /**
     * 打印纸一行最大的字节
     */
    private static final int LINE_BYTE_SIZE = 32;

    private static final int LEFT_LENGTH = 20;

    private static final int RIGHT_LENGTH = 12;

    /**
     * 左侧汉字最多显示几个文字
     */
    private static final int LEFT_TEXT_MAX_LENGTH = 8;

    /**
     * 小票打印菜品的名称,上限调到8个字
     */
    public static final int MEAL_NAME_MAX_LENGTH = 8;

    private static OutputStream outputStream = null;

    public static OutputStream getOutputStream() {
        return outputStream;
    }

    public static void setOutputStream(OutputStream outputStream) {
        PrintUtils.outputStream = outputStream;
    }


    /**
     * 打印文字
     *
     * @param text 要打印的文字
     */
    public static void printText(String text) {
        try {
            byte[] data = text.getBytes("gbk");
            outputStream.write(data, 0, data.length);
            outputStream.flush();
        } catch (IOException e) {
            //Toast.makeText(this.context, "发送失败!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 设置打印格式
     *
     * @param command 格式指令
     */
    public static void selectCommand(byte[] command) {
        try {
            outputStream.write(command);
            outputStream.flush();
        } catch (IOException e) {
            //Toast.makeText(this.context, "发送失败!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 复位打印机
     */
    public static final byte[] RESET = {0x1b, 0x40};

    /**
     * 左对齐
     */
    public static final byte[] ALIGN_LEFT = {0x1b, 0x61, 0x00};

    /**
     * 中间对齐
     */
    public static final byte[] ALIGN_CENTER = {0x1b, 0x61, 0x01};

    /**
     * 右对齐
     */
    public static final byte[] ALIGN_RIGHT = {0x1b, 0x61, 0x02};

    /**
     * 选择加粗模式
     */
    public static final byte[] BOLD = {0x1b, 0x45, 0x01};
    public static final byte[] BOLD1 = {0x1c, 0x21, 4};

    /**
     * 取消加粗模式
     */
    public static final byte[] BOLD_CANCEL = {0x1b, 0x45, 0x00};

    /**
     * 宽高加倍
     */
    public static final byte[] DOUBLE_HEIGHT_WIDTH = {0x1d, 0x21, 0x11};

    /**
     * 宽加倍
     */
    public static final byte[] DOUBLE_WIDTH = {0x1d, 0x21, 0x10};

    /**
     * 高加倍
     */
    public static final byte[] DOUBLE_HEIGHT = {0x1d, 0x21, 0x01};

    /**
     * 字体不放大
     */
    public static final byte[] NORMAL = {0x1d, 0x21, 0x00};

    /**
     * 设置默认行间距
     */
    public static final byte[] LINE_SPACING_DEFAULT = {0x1b, 0x32};

    /**
     * 设置行间距
     */
// public static final byte[] LINE_SPACING = {0x1b, 0x32};//{0x1b, 0x33, 0x14};  // 20的行间距(0,255)


// final byte[][] byteCommands = {
//       { 0x1b, 0x61, 0x00 }, // 左对齐
//       { 0x1b, 0x61, 0x01 }, // 中间对齐
//       { 0x1b, 0x61, 0x02 }, // 右对齐
//       { 0x1b, 0x40 },// 复位打印机
//       { 0x1b, 0x4d, 0x00 },// 标准ASCII字体
//       { 0x1b, 0x4d, 0x01 },// 压缩ASCII字体
//       { 0x1d, 0x21, 0x00 },// 字体不放大
//       { 0x1d, 0x21, 0x11 },// 宽高加倍
//       { 0x1b, 0x45, 0x00 },// 取消加粗模式
//       { 0x1b, 0x45, 0x01 },// 选择加粗模式
//       { 0x1b, 0x7b, 0x00 },// 取消倒置打印
//       { 0x1b, 0x7b, 0x01 },// 选择倒置打印
//       { 0x1d, 0x42, 0x00 },// 取消黑白反显
//       { 0x1d, 0x42, 0x01 },// 选择黑白反显
//       { 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°
//       { 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°
// };

    /**
     * 打印两列
     *
     * @param leftText  左侧文字
     * @param rightText 右侧文字
     * @return
     */
    @SuppressLint("NewApi")
    public static String printTwoData(String leftText, String rightText) {
        StringBuilder sb = new StringBuilder();
        int leftTextLength = getBytesLength(leftText);
        int rightTextLength = getBytesLength(rightText);
        sb.append(leftText);

        // 计算两侧文字中间的空格
        int marginBetweenMiddleAndRight = LINE_BYTE_SIZE - leftTextLength - rightTextLength;

        for (int i = 0; i < marginBetweenMiddleAndRight; i++) {
            sb.append(" ");
        }
        sb.append(rightText);
        return sb.toString();
    }

    /**
     * 打印三列
     *
     * @param leftText   左侧文字
     * @param middleText 中间文字
     * @param rightText  右侧文字
     * @return
     */
    @SuppressLint("NewApi")
    public static String printThreeData(String leftText, String middleText, String rightText) {
        StringBuilder sb = new StringBuilder();
        // 左边最多显示 LEFT_TEXT_MAX_LENGTH 个汉字 + 两个点
        if (leftText.length() > LEFT_TEXT_MAX_LENGTH) {
            leftText = leftText.substring(0, LEFT_TEXT_MAX_LENGTH) + "..";
        }
        int leftTextLength = getBytesLength(leftText);
        int middleTextLength = getBytesLength(middleText);
        int rightTextLength = getBytesLength(rightText);

        sb.append(leftText);
        // 计算左侧文字和中间文字的空格长度
        int marginBetweenLeftAndMiddle = LEFT_LENGTH - leftTextLength - middleTextLength / 2;

        for (int i = 0; i < marginBetweenLeftAndMiddle; i++) {
            sb.append(" ");
        }
        sb.append(middleText);

        // 计算右侧文字和中间文字的空格长度
        int marginBetweenMiddleAndRight = RIGHT_LENGTH - middleTextLength / 2 - rightTextLength;

        for (int i = 0; i < marginBetweenMiddleAndRight; i++) {
            sb.append(" ");
        }

        // 打印的时候发现,最右边的文字总是偏右一个字符,所以需要删除一个空格
        sb.delete(sb.length() - 1, sb.length()).append(rightText);
        return sb.toString();
    }

    /**
     * 获取数据长度
     *
     * @param msg
     * @return
     */
    @SuppressLint("NewApi")
    private static int getBytesLength(String msg) {
        return msg.getBytes(Charset.forName("GB2312")).length;
    }

    /**
     * 格式化菜品名称,最多显示MEAL_NAME_MAX_LENGTH个数
     *
     * @param name
     * @return
     */
    public static String formatMealName(String name) {
        if (TextUtils.isEmpty(name)) {
            return name;
        }
        if (name.length() > MEAL_NAME_MAX_LENGTH) {
            return name.substring(0, 8) + "..";
        }
        return name;
    }

}

2.xml布局、

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d4fbfb"
    android:paddingBottom="5dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="5dp"
    tools:context=".MainActivitydemo">

    <TextView
        android:id="@+id/textTip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/BkColor"
        android:text="@string/Tip"
        android:textSize="25sp" />

    <Spinner
        android:id="@+id/deviceSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textTip"
        android:layout_alignRight="@+id/InputText"
        android:layout_below="@+id/textTip" />

    <Button
        android:id="@+id/buttonConnect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonPrintTest"
        android:layout_alignLeft="@+id/buttonPrintTest"
        android:layout_alignRight="@+id/textTip"
        android:text="@string/Disconnected" />


    <Button
        android:id="@+id/buttonPrintTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textTip"
        android:layout_below="@+id/deviceSpinner"
        android:text="@string/PrinterTest" />

    <EditText
        android:id="@+id/InputText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textTip"
        android:layout_below="@+id/deviceSpinner"
        android:visibility="gone"
        android:layout_toLeftOf="@+id/buttonPrintTest"
        android:hint="@string/PrintContent"
        android:text="@string/Welcome" />

    <Button
        android:id="@+id/ButtonOpenCash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/buttonPrintTest"
        android:visibility="gone"
        android:layout_alignRight="@+id/buttonPrintTest"
        android:layout_below="@+id/buttonPrintTest"
        android:text="@string/OpenCash" />

    <Button
        android:id="@+id/ButtonCutPaper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ButtonOpenCash"
        android:layout_alignRight="@+id/ButtonOpenCash"
        android:layout_below="@+id/ButtonOpenCash"
        android:text="@string/CutPaper" />

    <TextView
        android:id="@+id/textXPrinter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/textTip"
        android:layout_alignTop="@+id/TextLogs"
        android:background="#03bcbc"
        android:gravity="bottom"
        android:text="@string/Logs" />

    <TextView
        android:id="@+id/TextLogs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/InputText"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@+id/textXPrinter"
        android:background="#03bcbc"
        android:text="@string/Logs" />


</RelativeLayout>

3.Activity实现、

package net.XPrinter.Example4bluetooth;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.bluetooth.*;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class MainActivitydemo extends Activity {
    /**
     * Called when the activity is first created.
     */

    private Button buttonPf = null;
    private Button buttonCash = null;
    private Button buttonCut = null;
    private Button buttonConnect = null;
    private EditText mprintfData = null;
    private TextView mprintfLog = null;
    private TextView mTipTextView = null;
    private Spinner mSpinner = null;
    private List<String> mpairedDeviceList = new ArrayList<String>();
    private ArrayAdapter<String> mArrayAdapter;
    private BluetoothAdapter mBluetoothAdapter = null; //创建蓝牙适配器
    private BluetoothDevice mBluetoothDevice = null;
    private BluetoothSocket mBluetoothSocket = null;
    OutputStream mOutputStream = null;
    private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private Builder dialog = null;
    Set<BluetoothDevice> pairedDevices = null;
    private String neirongcll;
    private String lym;

    private void PrintfLogs(String logs) {
        this.mprintfLog.setText(logs);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle(this.getTitle() + "(C)XPrinter.net");
        setContentView(R.layout.activity_maindemo);
        buttonPf = (Button) findViewById(R.id.buttonPrintTest);
        buttonCash = (Button) findViewById(R.id.ButtonOpenCash);
        buttonCut = (Button) findViewById(R.id.ButtonCutPaper);
        buttonConnect = (Button) findViewById(R.id.buttonConnect);
        mSpinner = (Spinner) findViewById(R.id.deviceSpinner);
        mprintfData = (EditText) findViewById(R.id.InputText);
        mprintfLog = (TextView) findViewById(R.id.TextLogs);
        mTipTextView = (TextView) findViewById(R.id.textTip);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        ButtonListener buttonListener = new ButtonListener();
        buttonPf.setOnClickListener(buttonListener);
        buttonCash.setOnClickListener(buttonListener);
        buttonCut.setOnClickListener(buttonListener);
        buttonConnect.setOnClickListener(buttonListener);
        setButtonEnadle(false);
        dialog = new Builder(this);
        dialog.setTitle("XPrinter hint:");
        dialog.setMessage(getString(R.string.XPrinterhint));
        dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
                //finish();
            }
        });

        dialog.setNeutralButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //finish();
            }
        });
        mpairedDeviceList.add(this.getString(R.string.PlsChoiceDevice));
        mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mpairedDeviceList);
        mSpinner.setAdapter(mArrayAdapter);
        mSpinner.setOnTouchListener(new Spinner.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (event.getAction() != MotionEvent.ACTION_UP) {
                    return false;
                }
                try {
                    if (mBluetoothAdapter == null) {
                        mTipTextView.setText(getString(R.string.NotBluetoothAdapter));
                        PrintfLogs(getString(R.string.NotBluetoothAdapter));
                    } else if (mBluetoothAdapter.isEnabled()) {
                        String getName = mBluetoothAdapter.getName();
                        pairedDevices = mBluetoothAdapter.getBondedDevices();
                        while (mpairedDeviceList.size() > 1) {
                            mpairedDeviceList.remove(1);
                        }
                        if (pairedDevices.size() == 0) {
                            dialog.create().show();
                        }
                        for (BluetoothDevice device : pairedDevices) {
                            // Add the name and address to an array adapter to show in a ListView
                            getName = device.getName() + "#" + device.getAddress();
                            lym=device.getName();
                            mpairedDeviceList.add(getName);//蓝牙名
                        }
                    } else {
                        PrintfLogs("BluetoothAdapter not open...");
                        dialog.create().show();
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    mprintfData.setText(e.toString());
                }
                return false;
            }
        });
    }

    private void setButtonEnadle(boolean state) {
        buttonPf.setEnabled(state);
        buttonCash.setEnabled(state);
        buttonCut.setEnabled(state);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消事件注册
        EventBus.getDefault().unregister(this);
    }


    class ButtonListener implements OnClickListener {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.buttonConnect: {
                    String temString = (String) mSpinner.getSelectedItem();
                    if (mSpinner.getSelectedItemId() != 0) {
                        if (buttonConnect.getText() != getString(R.string.Disconnected)) {
                            try {
                                mOutputStream.close();
                                mBluetoothSocket.close();
                                buttonConnect.setText(getString(R.string.Disconnected));
                                setButtonEnadle(false);
                            } catch (Exception e) {
                                // TODO: handle exception
                                PrintfLogs(e.toString());
                            }
                            return;
                        }
                        temString = temString.substring(temString.length() - 17);
                        try {
                            buttonConnect.setText(getString(R.string.Connecting));
                            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(temString);
                            mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(SPP_UUID);
                            mBluetoothSocket.connect();
                            buttonConnect.setText(getString(R.string.Connected));
                            setButtonEnadle(true);
                        } catch (Exception e) {
                            // TODO: handle exception
                            PrintfLogs(getString(R.string.Disconnected));
                            buttonConnect.setText(getString(R.string.Disconnected));
                            setButtonEnadle(false);
                            PrintfLogs(getString(R.string.ConnectFailed) + e.toString());
                        }

                    } else {
                        PrintfLogs("Pls select a bluetooth device...");
                    }
                }
                break;
                case R.id.buttonPrintTest: {
                    try {
                        if (mprintfData.getTextSize() == 0) {
                            PrintfLogs("Pls input print data...");
                        }
                        mOutputStream = mBluetoothSocket.getOutputStream();
                        PrintUtils PrintUtils=new PrintUtils();
                        PrintUtils.setOutputStream(mOutputStream);
                        PrintUtils.selectCommand(PrintUtils.RESET);
                        PrintUtils.selectCommand(PrintUtils.LINE_SPACING_DEFAULT);
                        PrintUtils.selectCommand(PrintUtils.ALIGN_CENTER);
                        PrintUtils.selectCommand(PrintUtils.BOLD1);
                        PrintUtils.printText("--#28和易生活外卖--\n\n");
                        PrintUtils.printText("妈妈味道\n\n");
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.printText("备注:多放香菜多放辣多放葱\n\n");
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.selectCommand(PrintUtils.BOLD_CANCEL);
                        PrintUtils.selectCommand(PrintUtils.NORMAL);
                        PrintUtils.selectCommand(PrintUtils.ALIGN_LEFT);
                        PrintUtils.printText(PrintUtils.printTwoData("订单编号", "201507161515\n"));
                        PrintUtils.printText(PrintUtils.printTwoData("下单时间", "2016-02-16 10:46\n"));
                        PrintUtils.printText(PrintUtils.printTwoData("人数:2人", "收银员:张三\n"));
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.selectCommand(PrintUtils.BOLD);
                        PrintUtils.printText(PrintUtils.printThreeData("项目", "数量", "金额\n"));
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.selectCommand(PrintUtils.BOLD_CANCEL);
                        PrintUtils.printText(PrintUtils.printThreeData("面", "1", "0.00\n"));
                        PrintUtils.printText(PrintUtils.printThreeData("米饭", "1", "6.00\n"));
                        PrintUtils.printText(PrintUtils.printThreeData("铁板烧", "1", "26.00\n"));
                        PrintUtils.printText(PrintUtils.printThreeData("一个测试", "1", "226.00\n"));
                        PrintUtils.printText(PrintUtils.printThreeData("牛肉面啊啊", "1", "2226.00\n"));
                        PrintUtils.printText(PrintUtils.printThreeData("牛肉面啊啊啊牛肉面啊啊啊", "888", "98886.00\n"));
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.printText(PrintUtils.printTwoData("合计", "53.50\n"));
                        PrintUtils.printText(PrintUtils.printTwoData("抹零", "3.50\n"));
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.printText(PrintUtils.printTwoData("应收", "50.00\n"));
                        PrintUtils.printText("--------------------------------\n");
                        PrintUtils.selectCommand(PrintUtils.ALIGN_LEFT);
                        PrintUtils.selectCommand(PrintUtils.BOLD1);
                        PrintUtils.printText(PrintUtils.printTwoData("地址:", "霸州市中悦国际和易生活结算中心二楼技术部\n曹先生:18744892420\n"));
                        PrintUtils.printText("\n\n\n\n\n");

                        PrintfLogs("Data sent successfully...");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        PrintfLogs(getString(R.string.PrintFaild) + e.getMessage());
                    }


                }
                break;
                case R.id.ButtonOpenCash: {
//                    startActivity(new Intent(MainActivitydemo.this, QIDong.class));
//             try {
//                if (mprintfData.getTextSize()==0) {
//                   PrintfLogs("Pls input print data...");
//                }
//                mOutputStream=mBluetoothSocket.getOutputStream();
//                mOutputStream.write(new byte[]{0x1b,0x70,0x00,0x1e,(byte)0xff,0x00});
//                mOutputStream.flush();
//                PrintfLogs("Data sent successfully...");
//             } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//                PrintfLogs(getString(R.string.OpenCashFaild)+e.getMessage());
//             }
                }
                break;
                case R.id.ButtonCutPaper: {
                    try {
                        if (mprintfData.getTextSize() == 0) {
                            PrintfLogs("Pls input print data...");
                        }
                        mOutputStream = mBluetoothSocket.getOutputStream();
                        mOutputStream.write(new byte[]{0x0a, 0x0a, 0x1d, 0x56, 0x01});
                        mOutputStream.flush();
                        PrintfLogs("Data sent successfully...");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        PrintfLogs(getString(R.string.CutPaperFaild) + e.getMessage());
                    }

                }
                break;
                default:
                    break;
            }

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

 

 

 

 

 

-------------------上诉贴上的代码稍微有点难度的都有注释,在这我就不太过于详细、

-------------------附上源码:http://download.csdn.net/download/android_cll/9903236

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶已初秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值