Android pad 连接蓝牙打印机Gprinter---实现蓝牙打印功能

Posted Algerhf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android pad 连接蓝牙打印机Gprinter---实现蓝牙打印功能相关的知识,希望对你有一定的参考价值。

一、概述

最近的项目有个需求,需要通过Android Pad连接佳博蓝牙打印机去实现打印功能。

首先想到的是要连接蓝牙,然后去调用API方法,在这里我使用的是GprinterSDK2.1的版本,而SDK2.2与SDK2.1

API有不同的地方,这里就以SDK 2.1为例。

二、使用

1、首先要导入jar包、添加依赖,如果没有SDK2.1的版本可以去http://download.csdn.net/download/zabio/9382570下载。


2、添加权限。

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

3、在AndroidManifest.xml文件中注册打印服务。

<service
    android:name="com.gprinter.service.GpPrintService"
    android:label="GpPrintService"
    android:process=":remote"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.gprinter.aidl.GpPrintService" />
    </intent-filter>
</service> 

4 新建包名为com.gprinter.aidl,向包中添加GpService.aidl文件,代码如下:

package com.gprinter.aidl;
interface GpService{  
    int openPort(int PrinterId,int PortType,String DeviceName,int PortNumber);
    void closePort(int PrinterId);
    int getPrinterConnectStatus(int PrinterId);
    int printeTestPage(int PrinterId);   
    int queryPrinterStatus(int PrinterId,int Timesout);
    int getPrinterCommandType(int PrinterId);
    int sendEscCommand(int PrinterId, String b64);
    int sendTscCommand(int PrinterId, String  b64); 
}
5、在你的BaseApplication的OnCreate方法里启动并绑定服务。
    private GpService                 mGpService = null;
    private PrinterServiceConnection  mConn = null;
    @Override
    public void onCreate() {
        super.onCreate();

        //开启打印服务
        startService();

        //绑定服务
        connection();
    }
    private void startService() {
        Intent i = new Intent(this, GpPrintService.class);
        this.startService(i);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void connection() {
        mConn = new PrinterServiceConnection();
        Intent intent = new Intent("com.gprinter.aidl.GpPrintService");
        intent.setPackage(this.getPackageName());
        this.bindService(intent, mConn, Context.BIND_AUTO_CREATE); // bindService
    }
    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("ServiceConnection", "called---onServiceDisconnected");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("ServiceConnection", "called--onServiceConnected");
            mGpService = GpService.Stub.asInterface(service);
        }
    }

6、点击打印按钮时首先要查询打印机的状态。

  private void print() {
        // 查询打印机状态
        if (!getPrinterStatusClicked()) {
            openPortDialogueClicked();
            return;
        }
        // 默认宽度384,汉字24*24 fontA 12*24  fontB 9*17  
        //这是打印命令的代码  暂时省略...
        Vector<Byte> datas = esc.getCommand(); // 发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = BaseApplication.mGpService.sendEscCommand(0, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];

            if (r != GpCom.ERROR_CODE.SUCCESS) {
                openPortDialogueClicked();
            } else {
                ToastUtils.showShort("打印成功");
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询打印机的状态,
     *
     * @return boolean true:打印机正常 false:打印机异常
     */
    public boolean getPrinterStatusClicked() {
        boolean flag = false;
        try {
            int status = BaseApplication.mGpService.queryPrinterStatus(0, 750);
            String str = "";
            if (status == GpCom.STATE_NO_ERR) {
                flag = true;
                str = "打印机正常";
                ToastUtils.showShort(str);
            } else if ((byte) (status & GpCom.STATE_OFFLINE) > 0) {
                str = "打印机脱机";
                ToastUtils.showShort(str);
            } else if ((byte) (status & GpCom.STATE_PAPER_ERR) > 0) {
                str = "打印机缺纸";
                ToastUtils.showShort(str);
            } else if ((byte) (status & GpCom.STATE_COVER_OPEN) > 0) {
                str = "打印机盖子未关";
                ToastUtils.showShort(str);
            } else if ((byte) (status & GpCom.STATE_ERR_OCCURS) > 0) {
                str = "打印机出错";
                ToastUtils.showShort(str);
            }
        } catch (RemoteException e1) {
            e1.printStackTrace();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            print();
        }
    }
<activity
    android:name=".mine.activity.PrinterConnectDialog"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Dialog" />
public class PrinterConnectDialog extends Activity {

    public static final String CONNECT_STATUS = "connect.status";

    public static final String ACTION_CONNECT_STATUS = "action.connect.status";

    public static PortParameters mPortParam;

    public static final int REQUEST_ENABLE_BT = 2;                        // 请求打开蓝牙的请求码

    private ImageView ivExist;
    private TextView  tvStatu;
    private ListView  lvPairedDevice;
    private Button    btDeviceScan;

    private BluetoothAdapter     mBluetoothAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

    private FindBlueToothReceiver mFindBlueToothReceiver;
    private BroadcastReceiver     mPrinterStatusBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.dialog_port);
        setFinishOnTouchOutside(false);

        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        initView();

        initData();

        initListener();
    }

    private void initView() {
        // 连接状态
        tvStatu = this.findViewById(R.id.tv_connect_statu);

        // 蓝牙设备列表
        lvPairedDevice = findViewById(R.id.lvPairedDevices);

        // 扫描按钮
        btDeviceScan = findViewById(R.id.btBluetoothScan);

        // 退出
        ivExist = this.findViewById(R.id.iv_printer_connect_exist);
    }

    private void initData() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 初始化端口信息
        initPortParam();

        // 注册广播
        registerBroadcast();

        // 初始化列表
        initList();
    }

    /**
     * 初始化端口参数
     */
    private void initPortParam() {
        Intent intent = getIntent();
        boolean state = intent.getBooleanExtra(CONNECT_STATUS, false);
        mPortParam = new PortParameters();
        PortParamDataBase database = new PortParamDataBase(this);
        mPortParam = database.queryPortParamDataBase("0");
        mPortParam.setPortType(PortParameters.BLUETOOTH);
        mPortParam.setPortOpenState(state);
    }

    private void registerBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_CONNECT_STATUS);
        if (mPrinterStatusBroadcastReceiver == null) {
            mPrinterStatusBroadcastReceiver = new PrinterStatusBroadcastReceiver();
        }
        this.registerReceiver(mPrinterStatusBroadcastReceiver, filter);
    }

    class PrinterStatusBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_CONNECT_STATUS.equals(intent.getAction())) {
                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);

                if (type == GpDevice.STATE_CONNECTED) {
                    Intent i = new Intent();
                    PrinterConnectDialog.this.setResult(RESULT_OK, i);
                    finish();
                }

                if (type == GpDevice.STATE_VALID_PRINTER) {
                    Intent i = new Intent();
                    PrinterConnectDialog.this.setResult(RESULT_OK, i);
                    finish();
                }

                if (type == GpDevice.STATE_CONNECTING) {
                    mPortParam.setPortOpenState(false);
                    tvStatu.setText(getResources().getString(R.string.connecting));
                } else if (type == GpDevice.STATE_NONE) {
                    mPortParam.setPortOpenState(false);
                    tvStatu.setText(getResources().getString(R.string.disconnected));
                } else if (type == GpDevice.STATE_VALID_PRINTER) {
                    mPortParam.setPortOpenState(true);
                    tvStatu.setText(getResources().getString(R.string.valid_printer));
                } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                    tvStatu.setText(getResources().getString(R.string.invalid_printer));
                } else if (type == GpDevice.STATE_CONNECTED) {
                    tvStatu.setText(getResources().getString(R.string.connected));
                }
            }
        }
    }

    /**
     * 初始化列表
     */
    private void initList() {

        //如果设备不支持蓝牙,就给出提示
        if (mBluetoothAdapter == null) {
            Toast.makeText(PrinterConnectDialog.this, getResources().getString(R.string.not_support_bluetooth), Toast.LENGTH_LONG).show();
            return;
        }

        //如果蓝牙未打开就去连接蓝牙,再获得已配对的蓝牙设备--否则就直接去获得已配对的蓝牙设备
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            getDeviceList();
        }
    }

    protected void getDeviceList() {
        if (mPairedDevicesArrayAdapter == null) {
            mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.bluetooth_device_name_item);
        }

        lvPairedDevice.setAdapter(mPairedDevicesArrayAdapter);

        if (mFindBlueToothReceiver == null) {
            mFindBlueToothReceiver = new FindBlueToothReceiver();
        }

        // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mFindBlueToothReceiver, filter);
        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mFindBlueToothReceiver, filter);

        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {

            for (BluetoothDevice device : pairedDevices) {
                if (device != null && !TextUtils.isEmpty(device.getName())) {
                    if (device.getName().startsWith("Gprinter")) {
                        mPairedDevicesArrayAdapter.add(device.getName() + "\\n" + device.getAddress());
                    }
                }

            }
        } else {
            String noDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
    }

    class FindBlueToothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (device.getName() != null && device.getName().startsWith("Gprinter")) {
                        //遍历之前的蓝牙列表,如果有,就不再添加改蓝牙设备
                        if (mPairedDevicesArrayAdapter.getCount() != 0) {
                            int count = 0;
                            for (int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++) {
                                String name = mPairedDevicesArrayAdapter.getItem(i);
                                if (name.equalsIgnoreCase(device.getName() + "\\n" + device.getAddress())) {
                                    count++;
                                }
                            }

                            //count为零,说明没有重复
                            if (count == 0) {
                                mPairedDevicesArrayAdapter.add(device.getName() + "\\n" + device.getAddress());
                            }

                        } else {
                            //没有数据时,直接添加数据
                            mPairedDevicesArrayAdapter.add(device.getName() + "\\n" + device.getAddress());
                        }
                    }
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

                //搜索蓝牙完成之后,让扫描按钮可点击
                btDeviceScan.setBackgroundResource(R.drawable.shape_btn_bg);
                btDeviceScan.setClickable(true);
                btDeviceScan.setText(getResources().getString(R.string.scan));

                //如果搜索完成后,蓝牙列表为零,添加未找到的item
                if (mPairedDevicesArrayAdapter != null && mPairedDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_bluetooth_device_found).toString();
                    mPairedDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    }

    private void initListener() {
        btDeviceScan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBluetoothAdapter == null) {
                    Toast.makeText(PrinterConnectDialog.this, getResources().getString(R.string.not_support_bluetooth), Toast.LENGTH_LONG).show();
                    return;
                }

                if (mPairedDevicesArrayAdapter == null) {
                    getDeviceList();
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    RxPermissions rxPermissions = new RxPermissions(PrinterConnectDialog.this);
                    rxPermissions.requestEach(
                            Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(@NonNull Permission permission) throws Exception {
                            if (permission.granted) {
                                startScan();
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                ToastUtils.showShort("Your refuse the access to the location,please try again!");

                            } else {
                                ToastUtils.showShort("Your refuse the access to the location,please try again!");
                            }
                        }
                    });
                } else {
                    startScan();
                }

            }
        });

        lvPairedDevice.setOnItemClickListener(mDeviceClickListener);

        ivExist.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void startScan() {
        // 如果蓝牙未打开,就去打开蓝牙,并获得已配对的蓝牙设备
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            // 如果蓝牙已经打开,让扫描按钮无法点击,然后扫描附近的蓝牙
            btDeviceScan.setBackgroundResource(R.drawable.shape_bg_disable);
            btDeviceScan.setClickable(false);
            btDeviceScan.setText(getResources().getString(R.string.discovering));

            // 如果蓝牙只剩下一个条目,我们需要判断它是否为 未配对的提示语或者未找到设备的提示语
            if (mPairedDevicesArrayAdapter != null && mPairedDevicesArrayAdapter.getCount() == 1) {
                String name = mPairedDevicesArrayAdapter.getItem(0);
                if (getResources().getText(R.string.none_paired).toString().equalsIgnoreCase(name)) {
                    mPairedDevicesArrayAdapter.remove(name);
                }

                if (getResources().getText(R.string.none_bluetooth_device_found).toString()
                        .equalsIgnoreCase(name)) {
                    mPairedDevicesArrayAdapter.remove(name);
                }
            }

            // 开始扫描
            discoveryDevice();
        }
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> av, View v,
                                int arg2, long arg3) {
            String str = tvStatu.getText().toString();
            if (str.equals(getResources().getString(R.string.connecting))) {
                ToastUtils.showShort(getResources().getString(R.string.connecting_notice));
                return;
            }

            if (mBluetoothAdapter == null) {
                Toast.makeText(PrinterConnectDialog.this, getResources().getString(R.string.not_support_bluetooth), Toast.LENGTH_LONG).show();
                return;
            } else {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableIntent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent,
                            REQUEST_ENABLE_BT);
                } else {
                    // Cancel discovery because it's costly and
                    // we're
                    // about to connect
                    mBluetoothAdapter.cancelDiscovery();
                    // Get the device MAC address, which is the
                    // last 17
                    // chars in the View
                    String info = ((TextView) v).getText()
                            .toString();
                    String noDevices = getResources().getText(
                            R.string.none_paired).toString();
                    String noNewDevice = getResources().getText(
                            R.string.none_bluetooth_device_found)
                            .toString();

                    if (!info.equals(noDevices)
                            && !info.equals(noNewDevice)) {
                        String address = info.substring(info
                                .length() - 17);
                        mPortParam.setBluetoothAddr(address);
                    }

                    Message message = new Message();
                    message.what = 1;
                    message.arg1 = 0;
                    mHandler.sendMessage(message);
                }
            }

        }
    };

    /**
     * 扫描蓝牙
     */
    private void discoveryDevice() {
        // If we're already discovering, stop it
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBluetoothAdapter.startDiscovery();
    }

    /**
     * 连接打印机设备
     */
    private void connectOrDisConnectToDevice() {
        if (BaseApplication.mGpService == null) {
            return;
        }
        int rel = 0;
        if (!mPortParam.getPortOpenState()) {
            if (CheckPortParamters(mPortParam)) {
                if (mPortParam.getPortType() == PortParameters.BLUETOOTH) {
                    try {
                        rel = BaseApplication.mGpService.openPort(0, mPortParam.getPortType(),
                                mPortParam.getBluetoothAddr(), 0);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
                if (r != GpCom.ERROR_CODE.SUCCESS) {
                    if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                        mPortParam.setPortOpenState(true);
                    }
                }
            } else {
                Toast.makeText(PrinterConnectDialog.this, R.string.port_parameters_wrong, Toast.LENGTH_LONG).show();
            }
        } else {
            try {
                BaseApplication.mGpService.closePort(0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    connectOrDisConnectToDevice();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private boolean CheckPortParamters(PortParameters param) {
        boolean rel = false;
        int type = param.getPortType();
        if (type == PortParameters.BLUETOOTH) {
            if (!param.getBluetoothAddr().equals("")) {
                rel = true;
            }
        }
        return rel;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                getDeviceList();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPrinterStatusBroadcastReceiver != null) {
            this.unregisterReceiver(mPrinterStatusBroadcastReceiver);
        }

        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }

        if (mFindBlueToothReceiver != null) {
            this.unregisterReceiver(mFindBlueToothReceiver);
        }
    }
}

dialog_port.xml文件如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/shape_round_white_8"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/shape_btlist_top">

        <TextView
            android:id="@+id/tv_connect_statu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:text="@string/device_list"
            android:textColor="@color/theme_white"
            android:textSize="20sp"
            android:typeface="serif" />

        <ImageView
            android:id="@+id/iv_printer_connect_exist"
            android:layout_width="@dimen/x40"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_marginRight="20dp"
            android:src="@mipmap/icon_close" />
    </RelativeLayout>

    <ListView
        android:id="@+id/lvPairedDevices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:divider="@color/theme_line"
        android:dividerHeight="1dp"
        android:stackFromBottom="true" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/theme_line" />

    <Button
        android:id="@+id/btBluetoothScan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/shape_btn_bg"
        android:text="@string/scan"
        android:textColor="@color/theme_white"
        android:textSize="20sp"
        android:typeface="serif" />

</LinearLayout>

bluetooth_device_name_item.xml如下
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/theme_text"
    android:textSize="18sp"
    android:typeface="serif"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
/>

shape_btn_bg.xml如下
<?xml version="1.0" encoding="utf-8"?>
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="5dp"/>
    <solid android:color="@color/theme_focus"/>
</shape>

<string name="connecting">连接中…</string>
    <string name="connecting_notice">"连接中,请不要重复点击!</string>
    <string name="connected">已连接</string>
    <string name="disconnected">连接断开,请重试!</string>
    <string name="valid_printer">打印机有效</string>
    <string name="invalid_printer">打印机无效</string>
    <string name="port_parameters_wrong">无效参数!</string>
    <string name="none_paired">没有配对</string>
    <string name="scan">扫描</string>
    <string name="discovering">扫描中</string>
    <string name="device_list">设备列表</string>
    <string name="none_bluetooth_device_found">蓝牙设备未找到</string>
    <string name="not_support_bluetooth">您的设置不支持蓝牙!</string>

7、打印命令方法参考如下:

8、关键代码是sendEscConmand方法的调用,不过SDK2.1打印条形码的长度有限制,所以可以自己生成我一维码图片让后去打

印: com.google.zxing包的一维码打印,导入jar包:可以网上下载

    private Bitmap getCodeBitMap(String str) {
       int size = str.length();
       for (int i = 0; i < size; i++) {
            int c = str.charAt(i);
            if ((19968 <= c && c < 40623)) {
                 // Toast.makeText(CreateCodeActivity.this, "生成条形码的时刻不能是中文", Toast.LENGTH_SHORT).show();
                 return null;
            }
        }
        Bitmap bmp = null;
        try {
             if (str != null && !"".equals(str)) {
                bmp = CreateOneDCode(str);
             }
        } catch (WriterException e) {
            e.printStackTrace();
	}
            return bmp;
    }

	/**
	 * 用于将给定的内容生成成一维码 注:目前生成内容为中文的话将直接报错,要修改底层jar包的内容
	 * 
	 * @param content
	 *            将要生成一维码的内容
	 * 
	 * @return 返回生成好的一维码bitmap
	 * @throws WriterException
	 *             WriterException异常
	 */


	public Bitmap CreateOneDCode(String content) throws WriterException {
		// 生成一维条码,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		BitMatrix matrix = null;
		matrix = new MultiFormatWriter().encode(content,BarcodeFormat.CODE_128, 260, 90);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                        if (matrix.get(x, y)) {
                            pixels[y * width + x] = mContext.getResources().getColor(R.color.black);
                        } else {
                            pixels[y * width + x] = mContext.getResources().getColor(R.color.white);	
                        }
		    }
		}

		Bitmap bitmap = Bitmap.createBitmap(width, height,
		Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}

三、后语

    之前写的有问题,重新编辑了一下。

以上是关于Android pad 连接蓝牙打印机Gprinter---实现蓝牙打印功能的主要内容,如果未能解决你的问题,请参考以下文章

android adb 支持蓝牙连接吗

Android使用蓝牙连接adb调试App

Android开发之蓝牙连接打印机

Android7蓝牙连接失败,蓝牙设备连接失败,只有首次运行能连接成功??

如何将不需要pin的蓝牙设备与android配对

Android:在 SPP 蓝牙设备之间切换