android 蓝牙通讯

核心类

public class BluetoothService {

    private static BluetoothService mInstance;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private CopyOnWriteArrayList<RequestCallback> mRequestCallbackList = new CopyOnWriteArrayList<>();
private BluetoothDevice mDevice;
    private BluetoothDevice mConnectDevice;
     //通讯双方约定
    private UUID mUuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private BluetoothSocket mSocket;
    private ExecutorService mExecutorService;
    private Thread mConnectThread;
    private ReadThread mReadThread;
    public void removeAll() {
        mRequestCallbackList.clear();
    }

    public interface RequestCallback {
        void onSuccess(byte[] bytes);
    }

    public void addRequestCallback(RequestCallback callback) {
        mRequestCallbackList.add(callback);
    }

    public void removeRequestCallback(RequestCallback callback) {
        mRequestCallbackList.remove(callback);
    }



    public static BluetoothService getInstance() {
        if (mInstance == null) {
            synchronized (BluetoothService.class) {
                if (mInstance == null) {
                    mInstance = new BluetoothService();
                }
            }
        }
        return mInstance;
    }

    public void setDevice(BluetoothDevice device) {
        mDevice = device;
    }

    public BluetoothDevice getDevice() {
        return mDevice;
    }

    private BluetoothService() {
        mExecutorService = Executors.newSingleThreadExecutor();
    }

    public void connect(BluetoothDevice device) {
        mConnectDevice = device;
        mConnectThread = new ConnectThread();
        mConnectThread.start();
    }

    //连接
    public class ConnectThread extends Thread {
        @Override
        public void run() {
            try {
                if (mSocket != null) {
                    mSocket.close();
                }
                mSocket = mConnectDevice.createRfcommSocketToServiceRecord(mUuid);
                mSocket.connect();
                if (mSocket.isConnected()) {
                    mOutputStream = mSocket.getOutputStream();
                    mInputStream = mSocket.getInputStream();
                    if (mReadThread == null) {
                        mReadThread = new ReadThread();
                        mReadThread.start();
                    }
                } else {
                    if (mSocket != null) {
                        mSocket.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    class ReadThread extends Thread {
        @Override
        public void run() {
            synchronized (this) {
                while (true) {
                    try {
                        boolean run = mSocket != null && mSocket.isConnected();
                        if (run) {
                            read();
                        }
                    } catch (Exception e) {
                        Logger.e(e.getMessage());
                    }
                }
            }
        }
    }

    public void read() throws IOException {
       /* byte[] buffer = new byte[1024];
        int read = mInputStream.read(buffer);
        byte[] count = new byte[read];
        System.arraycopy(buffer,0,count,0,read);
        String s = byte2HexStr(count);
        Logger.e("返回数据:"+s);*/
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        byte[] buffer = new byte[1];
        while ((len = mInputStream.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            byte[] bytes = out.toByteArray();

        }
    }


    public void disable() {
        if (mSocket != null) {
            mSocket.close();
        }
    }

    public synchronized void send(final byte[] bytes) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Logger.e("send = "+byte2HexStr(bytes));
                    mOutputStream.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

获取蓝牙列表

class BluetoothActivity : AppCompatActivity() {

    private var mDeviceList = arrayListOf<BluetoothDevice>()

    private var mBluetoothAdapter: BluetoothAdapter? = null

    private var mAdapter: DeviceAdapter? = null
    /**
     *  广播接收
     *  @see发现设备 [ACTION_FOUND]
     *  @see扫描完成 [ACTION_DISCOVERY_FINISHED]
     */
    private var mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(cxt: Context?, intent: Intent?) {
            val action = intent?.action
            when (action) {
                ACTION_FOUND -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(EXTRA_DEVICE)
                    if (!isAddDevice(device.address)) {
                        mDeviceList.add(device)
                        mAdapter?.notifyDataSetChanged()
                    }
                }
                ACTION_DISCOVERY_FINISHED ->mBluetoothAdapter?.cancelDiscovery()
                ACTION_ACL_CONNECTED -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(EXTRA_DEVICE)
                    mAdapter?.refresh(device)
                    BluetoothService.getInstance().device = device
                }
                ACTION_ACL_DISCONNECTED -> {
                    mAdapter?.refresh(null)
                    BluetoothService.getInstance().device = null
                }
                else -> return
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bluetooth)
        initView()
        initData()
        initEvent()
    }


    //注册广播
    private fun regReceiver() {
        val filter = IntentFilter()
        filter.addAction(ACTION_FOUND)//发现设备
        filter.addAction(ACTION_DISCOVERY_FINISHED)//扫描完成
        filter.addAction(ACTION_ACL_CONNECTED)//监听连接状态
        filter.addAction(ACTION_ACL_DISCONNECTED)//监听连接状态
        registerReceiver(mReceiver, filter)
    }

    //去除重复
    private fun isAddDevice(address: String): Boolean {
        mDeviceList.forEach {
            if (address == it.address) return true
        }
        return false
    }

    private fun initView() {
        tv_title.text = "蓝牙"

        regReceiver()
    }

    /**
     * 初始化蓝牙
     * @return true or false
     */
    private fun initBluetooth(): Boolean {
        val manager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?
        mBluetoothAdapter = manager?.adapter

        if (mBluetoothAdapter == null) {
            // 设备不支持蓝牙
            Logger.e("设备不支持蓝牙")
            return false
        }

        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            // 设备不支持蓝牙低功耗
            Logger.e("设备不支持蓝牙低功耗")
            return false
        }

        if (!mBluetoothAdapter!!.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, 100)
            return false
        }
        return true
    }

    /**
     * 找到已配对的设备
     */
    private fun findPairDevice() {
        val pairDevices = mBluetoothAdapter!!.bondedDevices
        pairDevices.forEach {
            mDeviceList.add(it)
            mAdapter?.notifyDataSetChanged()
        }
    }

    private fun initData() {
        mAdapter = DeviceAdapter(this, mDeviceList)
        listView.adapter = mAdapter
        if (initBluetooth()) {
            findPairDevice()//找到配对设备
            mBluetoothAdapter?.startDiscovery()//开启扫描
        }

        mAdapter?.refresh(BluetoothService.getInstance().device)
    }

    private fun initEvent() {
        btn_back.setOnClickListener { finish() }
        listView.setOnItemClickListener { _, _, position, _ ->
                mBluetoothAdapter?.cancelDiscovery()
                if (BluetoothService.getInstance().device?.address != null && mDeviceList[position].address == BluetoothService.getInstance().device.address) {
                    App.get().toast.show("蓝牙已连接")
                    return@setOnItemClickListener
                }
                App.get().toast.show("开始连接")
                BluetoothService.getInstance().connect(mDeviceList[position])
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100) {
            if (resultCode == Activity.RESULT_OK) {
                //蓝牙开启成功
                if (initBluetooth()) {
                    findPairDevice()//找到配对设备
                    mBluetoothAdapter?.startDiscovery()//开启扫描
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                //取消开启蓝牙
                Toast.makeText(this, "请打开蓝牙", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(mReceiver)
    }

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值