Android Bluetooth Development (II)

Posted by thepriest on Tue, 25 Jun 2019 00:14:01 +0200

Preface
In the previous two blogs, I briefly introduced some Api s in Bluetooth protocol and realized a simple chat function by using Bluetooth laundry. If you are not clear, you can read these two articles. Article 1: Bluetooth API Article 2: Using Bluetooth to Realize Simple Chat Function With the previous foundation, let's learn how to use Bluetooth to connect printers and print receipts.
Step 1: Authority
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
Step 2: Check if Bluetooth is turned on
Getting the Bluetooth adapter to decide whether to turn on Bluetooth or not, I won't post the code here. In the last article, I described in detail how to use the Bluetooth adapter to detect whether to turn on Bluetooth or not.
Step 3: Connect
When connecting, you need to search for nearby Bluetooth devices to connect. The specific operation is also introduced in the previous article.
Step 4:
Specify the text print format: Paste out the code first

public class TextFormatUtil {

    /**
 * The largest byte in a line of printed paper
 */
private static final int DEFAULT_LINE_BYTE_SIZE = 35;

private int lineByteSize = DEFAULT_LINE_BYTE_SIZE;
/**
 * Delimiter
 */
private static final String SEPARATOR = "$";

private static StringBuffer sb = new StringBuffer();
/**
 * Collection of row elements
 */
private final List<TextWeightBean> lineElements = new ArrayList<TextWeightBean>();

/**
 * The middle heading of typesetting
 *
 * @param title
 * @return
 */
public String getLineTitle(String title) {
    sb.delete(0, sb.length());
    for (int i = 0; i < (lineByteSize - getBytesLength(title)) / 2; i++) {
        sb.append(" ");
    }
    sb.append(title);
    sb.append("\n");
    return sb.toString();
}
/**
 * Print text according to specific gravity, align all text to the left
 *
 * @return
 */
public String getLineTextAccordingWeight(List<TextWeightBean> list) {
    sb.delete(0, sb.length());
    float totalWeight = 0;
    for (int i = 0; i < list.size(); i++) {
        totalWeight += list.get(i).getWeight();
    }
    for (int i = 0; i < list.size(); i++) {
        TextWeightBean textWeightBean = list.get(i);
        String showText = textWeightBean.getText();
        int holdSize = (int) (textWeightBean.getWeight() / totalWeight * lineByteSize);
        showText = formatText(showText, holdSize);
        sb.append(showText);
    }
    sb.append("\n");
    return sb.toString();
}
/**
 * Text formatting for display
 * @param showText
 * @param holdSize
 * @return
 */
private String formatText(String showText, int holdSize) {
    int textSize = getBytesLength(showText);
    if (textSize > holdSize) {
        showText = subText(showText, holdSize);
    } else {
        for (int j = 0; j < holdSize - textSize; j++) {
            showText += " ";
        }
    }
    return showText;
}
private String subText(String showText, int holdSize) {
    int size = 0;
    int index = 0;
    int symbolLength = "..".getBytes(Charset.forName("GB2312")).length;
    for (int j = 0; j < showText.length(); j++) {
        String c = showText.substring(j, j + 1);
        size += c.getBytes(Charset.forName("GB2312")).length;
        index = j;
        if (size > holdSize - symbolLength) {
            break;
        }
    }
    showText = showText.substring(0, index) + "..";

    return formatText(showText, holdSize);
}   
/**
 * Get data length
 * @param msg
 * @return
 */
@SuppressLint("NewApi")
private static int getBytesLength(String msg) {
    if (msg == null) {
        return "null".getBytes(Charset.forName("GB2312")).length;
    }
    return msg.getBytes(Charset.forName("GB2312")).length;
}
/**
 * Get the maximum length
 * @param msgs
 * @return
 */
private static int getMaxLength(Object[] msgs) {
    int max = 0;
    int tmp;
    for (Object oo : msgs) {
        tmp = getBytesLength(oo.toString());
        if (tmp > max) {
            max = tmp;
        }
    }
    return max;
}

}

Step 4: Specify the image format
The step of specifying image format was introduced in the previous article. If you don't understand it, you can see this article. http://blog.csdn.net/qq_34942689/article/details/72820226

Step 5: Printing

private void sendMessage(String message) {
    if (message.length() > 0) {
        // Get the message bytes and tell the BluetoothService to write
        byte[] send;
        try {
            send = message.getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            send = message.getBytes();
        }
        bluetoos.getService(this).write(send);
    }

Finally, the sendMessage method can be invoked where you need to print.
Above is the whole use of Bluetooth to connect the printer to print the ticket function, there are unclear places or any better suggestions welcome to leave a message, thank you!

Topics: Android