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

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

资源下载地址:点击下载

扫描,显示蓝牙列表

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));
        }

资源下载地址:点击下载

猜你喜欢

转载自blog.csdn.net/shu_quan/article/details/83303338