public abstract class BaseChengActivity {

//普通电子称 蓝牙连接时需要用的UUID
public static final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
public BluetoothAdapter btAdapt;
public List<String> lstDevices = new ArrayList<String>();
public PrintAdapter printAdapter;
public ChengCallBack printCallBack;
public ConnectThread connectThread;
public AcceptThread acceptThread;

public void registerPrintCallBack(ChengCallBack printCallBack) {
    this.printCallBack = printCallBack;
}

public void Bluetooth() {
    btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
    IntentFilter intent = new IntentFilter();
    intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
    intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(searchDevices, intent);
    acceptThread = new AcceptThread();
    acceptThread.start();
}

public BroadcastReceiver searchDevices = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Bundle b = intent.getExtras();
        Object[] lstName = b.keySet().toArray();
        for (int i = 0; i < lstName.length; i++) {
            String keyName = lstName[i].toString();
            Log.e(keyName, String.valueOf(b.get(keyName)));
        }
        BluetoothDevice device = null;
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                if (device.getName() != null) {
                    String str = "未配对[" + device.getName() + "]" + device.getAddress();
                    if (lstDevices.indexOf(str) == -1) {// 防止重复添加{
                        lstDevices.add(str);
                    } // 获取设备名称和mac地址}
                    printAdapter.notifyDataSetChanged();
                }
                try {
                    ClsUtils.setPin(device.getClass(), device, "0000");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    ClsUtils.cancelPairingUserInput(device.getClass(), device);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (device.getBondState()) {
                case BluetoothDevice.BOND_BONDING:
                    Log.d("BlueToothTestActivity", "正在配对");
                    break;
                case BluetoothDevice.BOND_BONDED:
                    Log.d("BlueToothTestActivity", "完成配对");
                    connect(device);//连接设备
                    break;
                case BluetoothDevice.BOND_NONE:
                    Log.d("BlueToothTestActivity", "取消配对");
                default:
                    break;
            }
        }
        if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
            BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            try {
                ClsUtils.setPin(btDevice.getClass(), btDevice, "0000"); // 手机和蓝牙采集器配对
                ClsUtils.createBond(btDevice.getClass(), btDevice);
                ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
};

public class ItemLongClickEvent implements AdapterView.OnItemLongClickListener {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (btAdapt.isDiscovering())
            btAdapt.cancelDiscovery();
        String str = lstDevices.get(position);
        String str1 = str.substring(0, str.indexOf("]"));
        String str2 = str.substring(str1.length() + 1, str.length());
        String address = str2;
        //取消配对
        BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
        try {
            ClsUtils.removeBond(btDev.getClass(), btDev);
            setAdapter();
        } catch (Exception e) {
            Log.e("Darren", e.toString());
        }
        return true;
    }
}

/**
 * 点击连接蓝牙设备
 */
public class ItemClickEvent implements AdapterView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (btAdapt.isDiscovering()) btAdapt.cancelDiscovery();
        String str = lstDevices.get(position);
        String str1 = str.substring(0, str.indexOf("]"));
        String str2 = str.substring(str1.length() + 1, str.length());
        String address = str2;
        BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
        try {
            if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
                ClsUtils.pair(address, "0000");
            } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) {
                connect(btDev);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 搜索
 */
public class ClickEvent implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        setAdapter();
    }
}

/**
 * 搜索蓝牙
 */
public void setAdapter() {
    if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
        lstDevices.clear();
        printAdapter.notifyDataSetChanged();
        return;
    }
    if (btAdapt.isDiscovering())
        btAdapt.cancelDiscovery();
    lstDevices.clear();
    Object[] lstDevice = btAdapt.getBondedDevices().toArray();
    for (int i = 0; i < lstDevice.length; i++) {
        BluetoothDevice device = (BluetoothDevice) lstDevice[i];
        String str = "已配对[" + device.getName() + "]" + device.getAddress();
        lstDevices.add(str); // 获取设备名称和mac地址
        printAdapter.notifyDataSetChanged();
    }
    setTitle("本机蓝牙地址:" + btAdapt.getAddress());
    btAdapt.startDiscovery();
}

/**
 * 解析数据
 *根据返回的数据解析 我这里返回的格式是 =256.00=
 * @param data
 * @return
 */
public String dataProcess(String data) {
    String ret = "0.00";
    try {
        String[] _data = new String[]{};
        if (data.contains("=")) {
            _data = data.split("=");
        }
        if (_data.length == 0) {
            return ret;
        } else {
            for (String x : _data) {
                int length = x.length();
                if (length > 6) {
                    String subx = x.substring(0, 6);
                    String reverse = new StringBuffer(subx).reverse().toString();
                    double dou = Double.parseDouble(reverse) * 2;
                    ret = String.format("%.2f", dou);
                }
            }
        }
        return ret;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return ret;
}

/**
 * 连接
 *
 * @param btDev
 */
public void connect(BluetoothDevice btDev) {
    try {
        Log.e("Darren-","连接中....");
        BluetoothSocket socket = btDev.createRfcommSocketToServiceRecord(BT_UUID);
        connectThread = new ConnectThread(socket, true);
        connectThread.start();
    } catch (Exception e) {
    }
}

/**
 * 获取电子秤数据
 */
private class ConnectThread extends Thread {
    private BluetoothSocket mmSocket;
    private boolean activeConnect;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    private ConnectThread(BluetoothSocket socket, boolean connect) {
        mmSocket = socket;
        this.activeConnect = connect;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {

        }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    @Override
    public void run() {
        btAdapt.cancelDiscovery();
        try {
            if (activeConnect) {
                mmSocket.connect();
            }
            printCallBack.onChengSuccess();
            byte[] buffer = new byte[1024];// buffer store for the stream
            int bytes;// bytes returned from read()
            while (true) {
                bytes = mmInStream.read(buffer);
                if (bytes > 0) {
                    final byte[] data = new byte[bytes];
                    System.arraycopy(buffer, 0, data, 0, bytes);
                    printCallBack.onChengScan(dataProcess(new String(data)));
                }
                sleep(150);
            }
        } catch (IOException | InterruptedException connectException) {
            try {
                mmSocket.close();
                printCallBack.onChengFail();
            } catch (IOException closeException) {
            }
            return;
        }
    }

    /**
     * Will cancel an in-progress connection, and close the socket
     */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
        }
    }
}

/**
 * 监听线程
 */
private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            tmp = btAdapt.listenUsingRfcommWithServiceRecord("NAME", BT_UUID);
        } catch (IOException e) {
        }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        try {
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                    printCallBack.onChengConnecting();
                } catch (IOException e) {
                    break;
                }
                if (socket != null) {
                    connectThread = new ConnectThread(socket, false);
                    connectThread.start();
                    mmServerSocket.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) {
        }
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    //取消搜索
    if (btAdapt != null && btAdapt.isDiscovering()) {
        btAdapt.cancelDiscovery();
    }
    //注销BroadcastReceiver,防止资源泄露
    unregisterReceiver(searchDevices);
    if (null != acceptThread)
        acceptThread.cancel();
    if (null != connectThread)
        connectThread.cancel();
}
Copy the code

}