Android 蓝牙二维码打印,打印图片,二维码加文字布局,蓝牙连接

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shu_quan/article/details/83303338

蓝牙二维码打印,工厂物料条码,绝对好用

资源下载地址:点击下载

扫描,显示蓝牙列表

public class DeviceListActivity extends AppCompatActivity {
    private static final String TAG = "DeviceListActivity";
    private static final boolean D = true;

    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.device_list);
        setResult(Activity.RESULT_CANCELED);

        Button scanButton = (Button) findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                doDiscovery();
                v.setVisibility(View.GONE);
            }
        });

        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
                R.layout.device_name);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
                R.layout.device_name);

        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);

        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                // if (device.getName().contains("K319")) {  不过滤
                mPairedDevicesArrayAdapter.add(device.getName() + "\n"
                        + device.getAddress());
                // }
            }
        } else {
            mPairedDevicesArrayAdapter.add("没有匹配的设备");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

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

        this.unregisterReceiver(mReceiver);
    }

    private void doDiscovery() {
        if (D)
            Log.d(TAG, "doDiscovery()");

        setProgressBarIndeterminateVisibility(true);
        setTitle("扫描设备...");
        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        mBtAdapter.startDiscovery();
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            mBtAdapter.cancelDiscovery();

            // View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (device == null) {
                        return;
                    }
                    if (!TextUtils.isEmpty(device.getName())) {
                        mNewDevicesArrayAdapter.add(device.getName() + "\n"
                                + device.getAddress());
                    }
                    //不过滤
                   /* if (!TextUtils.isEmpty(device.getName())) {
                        if (device.getName().contains("K319")) {

                        }
                    }*/
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle("选择连接的设备");
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    mNewDevicesArrayAdapter.add("没有匹配的设备");
                }
            }
        }
    };

}

蓝牙连接

package com.pad.untek.mes.mespda.printqrcode.ble;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.pad.untek.mes.mespda.printqrcode.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConnectBleActivity extends AppCompatActivity {
    // 来自蓝牙服务处理程序的消息类型
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // 来自蓝牙服务处理程序的关键名称。
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // 意图请求代码
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    @BindView(R.id.tv_conn_name)
    TextView tvConnName;
    @BindView(R.id.btn_add_print)
    Button btnAddPrint;


    // 连接设备的名称
    private String mConnectedDeviceName = null;
    //本地蓝牙适配器
    private BluetoothAdapter mBluetoothAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect_ble);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "您的设备不支持蓝牙", Toast.LENGTH_LONG).show();
            return;
        }
        if (BluetoothUtis.getInstances().device != null) {
            btnAddPrint.setText("断开连接");
            tvConnName.setText("已连接" + BluetoothUtis.getInstances().device.getName());
        }
    }

    // 从蓝牙服务中获取信息的处理程序。
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED:
                            btnAddPrint.setText("断开连接");
                            tvConnName.setText("已连接:");
                            tvConnName.append(mConnectedDeviceName);
                            break;
                        case BluetoothService.STATE_CONNECTING:
                            tvConnName.setText("正在连接...");
                            break;
                        case BluetoothService.STATE_LISTEN://异常
                            tvConnName.setText("连接失败");
                            BluetoothUtis.getInstances().device = null;
                            btnAddPrint.setText("扫描连接");
                            break;
                        case BluetoothService.STATE_NONE:
                            tvConnName.setText("未连接蓝牙");
                            btnAddPrint.setText("扫描连接");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    break;
                case MESSAGE_READ:
                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    tvConnName.setText(mConnectedDeviceName);
                    Toast.makeText(getApplicationContext(), "连接至" + mConnectedDeviceName, Toast.LENGTH_SHORT)
                            .show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(),
                            msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                            .show();
                    break;
            }

            return false;
        }
    });


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) {
                    String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                    BluetoothUtis.getInstances().mService.connect(device);
                    BluetoothUtis.getInstances().device = device;
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_LONG);
                } else {
                    Toast.makeText(this, "蓝牙没有打开", Toast.LENGTH_LONG);
                    finish();
                }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!mBluetoothAdapter.isEnabled()) {
            // 打开蓝牙
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        if (BluetoothUtis.getInstances().mService == null) {
            BluetoothUtis.getInstances().mService = new BluetoothService(this, mHandler);
            BluetoothUtis.getInstances().mService.printLeft();//居中
        }
    }

    //连接设备
    @OnClick(R.id.btn_add_print)
    public void onClick() {
        if (BluetoothUtis.getInstances().device == null) {
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
        } else {
            BluetoothUtis.getInstances().mService.stop();
            BluetoothUtis.getInstances().device = null;
        }
    }
}

蓝牙工具,连接和打印

package com.pad.untek.mes.mespda.printqrcode.ble;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.Toast;

/**
 * 淑全 on 2018/5/24.
 */

public class BluetoothUtis {


    public BluetoothService mService = null;
    private static BluetoothUtis instance = null;
    public BluetoothDevice device = null;

    private BluetoothUtis() {
    }

    public static BluetoothUtis getInstances() {
        if (null == instance) {
            instance = new BluetoothUtis();
        }
        return instance;
    }

    public boolean isService(Context context) {
        if (mService == null || mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(context, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public boolean sendMessage(Context context, Bitmap bitmap) {
        if (mService == null || mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(context, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            // 发送打印图片前导指令
            byte[] start = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x40, 0x1B, 0x33, 0x00};
            mService.write(start);
            mService.printLeft();
            byte[] draw2PxPoint = PicFromPrintUtils.draw2PxPoint(bitmap);
            mService.write(draw2PxPoint);
            byte[] end = {0x1D, 0x0C};//走纸
            BluetoothUtis.getInstances().mService.write(end);
            // 发送结束指令
            byte[] ends = {0x1B, 0x40};
            BluetoothUtis.getInstances().mService.write(ends);
            return true;
        }
    }

}

发送打印

 boolean flag = BluetoothUtis.getInstances().isService(this);//判断蓝牙是否连接
        if (flag) {
            //打印
            boolean b = BluetoothUtis.getInstances().sendMessage(MainActivity.this, bbb);
            Toast.makeText(this, b ? "打印成功" : "打印失败", Toast.LENGTH_LONG).show();
        } else {
            startActivity(new Intent(this, ConnectBleActivity.class));
        }

资源下载地址:点击下载

 

 

 

展开阅读全文

Andriod 实现操作 蓝牙打印打印二维码

03-16

1.使用的是 毕索龙R200ll 蓝牙打印机,通过在手机端输入 字符内容 ,点击打印,实现在蓝牙打印机打印出相应的二维码。rn2.现在已经实现:在手机上可以根据输入内容,成功生成相应二维码。rn3.问题是:我试着将生成的二维码图片转换成bite[]数组,输出给蓝牙打印机打印,出现了问题。rn4.请各位大神帮忙解决下这个问题,谢谢。rn以下是我将二维码转换成bite[]数组的方法:rnpublic static byte[] draw2PxPoint(Bitmap bit) rn byte[] data = new byte[16290];rn int k = 0;rn for (int j = 0; j < 15; j++) rn data[k++] = 0x1B;rn data[k++] = 0x2A;rn data[k++] = 33; // m=33时,选择24点双密度打印,分辨率达到200DPI。rn data[k++] = 0x68;rn data[k++] = 0x01;rn for (int i = 0; i < 360; i++) rn for (int m = 0; m < 3; m++) rn for (int n = 0; n < 8; n++) rn byte b = px2Byte(i, j * 24 + m * 8 + n, bit);rn data[k] += data[k] + b;rn rn k++;rn rn rn data[k++] = 10;rn rn return data;rn rn public static byte px2Byte(int x, int y, Bitmap bit) rn byte b;rn int pixel = bit.getPixel(x, y);rn int red = (pixel & 0x00ff0000) >> 16; // 取高两位rn int green = (pixel & 0x0000ff00) >> 8; // 取中两位rn int blue = pixel & 0x000000ff; // 取低两位rn int gray = RGB2Gray(red, green, blue);rn if ( gray < 128 )rn b = 1;rn else rn b = 0;rn rn return b;rn rn private static int RGB2Gray(int r, int g, int b)rn int gray = (int) (0.29900 * r + 0.58700 * g + 0.11400 * b); //灰度转化公式rn return gray;rn 论坛

打印二维码到小票上

05-04

用XtraReport的时候我会用,我用的是第三方的QRCode控件,所以只要设置PictureBox的数据源就可以了。rn this.xrPictureBoxCode.Image = qrcode.QREncoder(strMeasureDocID);rnqrcode.QREncoder()方法是用来生成二维码的。现在我用立象A2240E串口打印机,必须要用它的接口函数才行,其中有一个A_Get_Graphic()函数是可以打印图片,但是必须是来自计算机上的文件。我不想存到硬盘上在打印,能不能在缓存里直接打印呢?rn下面是接口文档里A_Get_Graphic()函数的介绍。rnrn *******************************************************************************rn A_Get_Graphic()rn ===============================================================================rn PURPOSE Download graph data from PC into the printer's RAM or Flash memory.rnrn SYNTAXrn VC:rn int A_Get_Graphic(int x, int y, int mem_mode, char format, LPCTSTRrn filename);rn VB:rn Declare Function A_Get_Graphic(ByVal x As Long, ByVal y As Long, ByValrn mem_mode As Long, ByVal format As Byte, ByVal filename Asrn String) As Longrnrn PARAMETERrn x; X coordinate.rn y; Y coordinate.rn mem_mode; Memory mode, 1 => RAM, 2 => Flash Memoryrn Notice: The flash writing lifespan is limited, unlessrn for special applications that require storern in Flash memory then recall in another procedure,rn for general printing, it's strongly recommendedrn that all graphics being download into RAM.rn format; Image file format.rn +------+---------------------+---------+rn |format|Image File Format |Direction|rn +------+---------------------+---------+rn | B |8-bit BMP file format|flipped |rn +------+---------------------+---------+rn | b |8-bit BMP file format| |rn +------+---------------------+---------+rn | I |8-bit IMG file format|flipped |rn +------+---------------------+---------+rn | i |8-bit IMG file format| |rn +------+---------------------+---------+rn | P |8-bit PCX file format|flipped |rn +------+---------------------+---------+rn | p |8-bit PCX file format| |rn +------+---------------------+---------+rn filename; File name of graphic data with path.rn The format is XXXXXXXX.XXX or X:\XXX\XXX.XXXrnrn RETURN 0 -> OK.rn Reference AW-Error.txt file.rnrn EXAMPLErn VC:rn A_Get_Graphic(275,50,1,'B',"bb.bmp");rn VB:rn Call A_Get_Graphic(275,50,1,66,"bb.bmp")rn The 'B' ASCII code is 66.rnrn REMARK The Get_Graphic function will store graphic object in RAM memory. 论坛

没有更多推荐了,返回首页