Android 热敏打印机开发(蓝牙)

前言

由于自己工作原因,涉及到热敏打印机开发,因此自己写了一套热敏打印机SDK,目前暂时只支持蓝牙打印
我生成了jar包的形式,方便大家使用。里面代码的实现原理现在暂无时间去讲解,主要以如何使用为主。后面将会开源,现在没时间。大家可以关注我,后期将会更新
SDK
源码地址
链接:https://pan.baidu.com/s/1vUu7AtNsdP9zThbN0R3Uew
提取码:y2jn
注意事项
目前只适配了蓝牙打印机,58型号的,后期会跟上。。。80的也可以打印就是了
已完成功能
扫描蓝牙
打印一行,打印一行两列,打印一行三列,打印图片,打印条形码。。。
未完成功能
打印二维码(目前需要打印的只能通过图片打印方式进行,貌似58是不支持打印二维码的)

效果图

Android 热敏打印机开发(蓝牙)_第1张图片

步骤

如何导入jar包我就不说了。权限



Android 热敏打印机开发(蓝牙)_第2张图片

package com.thomas.printer.demo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.thomas.printer.PrinterCommand;
import com.thomas.printer.PrinterService;
import com.thomas.printer.binder.PrinterBinder;
import com.thomas.printer.bluetooth.BluetoothScanCallback;
import com.thomas.printer.callback.IConnectCallback;
import com.thomas.printer.callback.ProcessData;
import com.thomas.printer.callback.TaskCallback;
import com.thomas.printer.factory.PrinterManufacturers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private ListView unpaired_list;
    private ProgressBar progress_bar;
    private List> mapList = new ArrayList<>();
    private SimpleAdapter simpleAdapter;

    private PrinterBinder binder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (PrinterBinder) service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unpaired_list = findViewById(R.id.unpaired_list);
        progress_bar = findViewById(R.id.progress_bar);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        
        initService();
        initView();
    }


    private void initView() {
        simpleAdapter = new SimpleAdapter(this,
                mapList,
                R.layout.item_paired_device,
                new String[]{"deviceName","deviceAddress","deviceType","deviceBondState","printerState"},
                new int[]{R.id.item_paired_name,R.id.item_paired_address,R.id.item_paired_type,R.id.item_paired_state,R.id.item_printer_state});
        unpaired_list.setAdapter(simpleAdapter);
        unpaired_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int position, long id) {
                if (mapList.size() > 0){
                    connectDevice(position);

                }


            }
        });
    }

    private void initService() {
        Intent intent = new Intent(this, PrinterService.class);
        bindService(intent,connection,BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_print:
                    printMenu();

                    break;
                case R.id.menu_refresh:
                    refreshDevice();

                    break;
            }
            return false;
        }
    };

    private void printMenu() {
        binder.writeSendBluetoothData(new TaskCallback() {
            @Override
            public void onSucceed() {

            }

            @Override
            public void onFailed() {

            }
        }, new ProcessData() {
            @Override
            public List processDataBeforeSend(PrinterCommand printer) {
                List list = new ArrayList<>();
                printer.setPrinterManufacturers(PrinterManufacturers.XPrinter);
                try {
                    list.add(printer.initPrint());
                    // 黑白反显
                    list.add(printer.setWhiteOnBlack());
                    list.add(printer.normalText("我的店铺\n",3,1,true));
                    list.add(printer.cancelWhiteOnBlack());
                    list.add(printer.normalText("我的店铺\n",3,1,true));


                    list.add(printer.normalText("----------------\n",3,1,true));

                    list.add(printer.printThreeColumn("name" , "count" , "money",1));
                    for (int i = 0; i< 4; i++){
                        list.add(printer.printThreeColumn("iphone6_" + i, "X" + i, "4999.00",1));
                    }
                    for (int i = 0; i< 3; i++){
                        list.add(printer.printThreeColumn("iphoneXRXRXRXR_" + i, "X" + i, "4999.00",1));
                    }
                    list.add(printer.normalText("----------------\n",3,1,true));


                    list.add(printer.printTwoColumn("总价","11111",1));
                    list.add(printer.printTwoColumn("总数","8",1));

                    list.add(printer.printBarCode("{B123",1,3,80));

                    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_connect);
                    list.add(printer.printBitmap(bmp));
                    list.add(printer.normalText("------end------\n",3,1,true));
                    list.add(printer.printAndFeedLine());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return list;
            }
        });
    }

    private void refreshDevice() {
        try {
            binder.onScanBluetoothDevice(new BluetoothScanCallback() {
                @Override
                public void onScanning() {
                    // 扫描中
                    progress_bar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onScanFinish() {
                    // 扫描结束
                    progress_bar.setVisibility(View.GONE);
                }

                @Override
                public void onScanning(BluetoothDevice bluetoothDevice) {
                    // 扫到的蓝牙设备
                    boolean contain = false;
                    for (Map map : mapList){
                        if (map.get("deviceAddress").equals(bluetoothDevice.getAddress())){
                            contain = true;
                        }
                    }
                    if (!contain){
                        Map map = new HashMap<>();
                        map.put("deviceName",bluetoothDevice.getName());
                        map.put("deviceAddress",bluetoothDevice.getAddress());
                        map.put("deviceType", acquireDeviceType(bluetoothDevice.getType()));
                        map.put("deviceBondState",acquireBondState(bluetoothDevice.getBondState()));
                        map.put("printerState","未连接");
                        mapList.add(map);
                        simpleAdapter.notifyDataSetChanged();

                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void connectDevice(final int position) {
        String address = mapList.get(position).get("deviceAddress").toString();
        binder.onConnectBluetoothDevice(address, new IConnectCallback() {
            @Override
            public void onConnecting() {

            }

            @Override
            public void onConnectResult(boolean success) {
                // 设备连接是否成功
                mapList.get(position).put("printerState","连接状态"+success);
                simpleAdapter.notifyDataSetChanged();

            }

            @Override
            public void onLostConnect(BluetoothSocket bluetoothSocket) {
                // 中间发生断开
                mapList.get(position).put("printerState","连接状态false");
                simpleAdapter.notifyDataSetChanged();
            }

            @Override
            public void onConnectStatus(BluetoothSocket bluetoothSocket, String status) {
                // 连接状态

            }
        });
    }

    public String acquireDeviceType(int type) {
        String deviceType;
        switch (type){
            case BluetoothDevice.DEVICE_TYPE_CLASSIC:
                deviceType = getString(R.string.classic_bluetooth);
                break;
            case BluetoothDevice.DEVICE_TYPE_LE:
                deviceType = getString(R.string.low_power_bluetooth);
                break;
            case BluetoothDevice.DEVICE_TYPE_DUAL:
            default:
                deviceType = getString(R.string.dual_bluetooth);
                break;
        }
        return deviceType;

    }

    /**
     * @param bondState device bond state
     * @return state
     */
    public String acquireBondState(int bondState) {
        String state;
        switch (bondState){
            case BluetoothDevice.BOND_BONDING:
                state = getString(R.string.bonding);
                break;
            case BluetoothDevice.BOND_BONDED:
                state = getString(R.string.bonded);
                break;
            case BluetoothDevice.BOND_NONE:
            default:
                state = getString(R.string.unpaired);
                break;
        }
        return state;
    }
}

你可能感兴趣的:(java,蓝牙,android,android,studio)