Android蓝牙连接汽车OBD设备

Stella981
• 阅读 788
//设备连接
public class BluetoothConnect implements Runnable {

    private static final UUID CONNECT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private Loger loger = Loger.getLoger();
    private BluetoothDevice mDevice;
    private BluetoothSocket mSocket;
    private IInterface iInterface;
    private OutputStream out;
    private boolean isConnected = false;

    public BluetoothConnect(BluetoothDevice device) {
        this.mDevice = device;
    }

    public interface IInterface {

        void connected(BluetoothDevice device);
        
        void receive(String string);
        
        void disconnect(BluetoothDevice device);
        
        void connectError();
    }
    
    @Override
    public void run() {
        try {
            if (iInterface == null) {
                loger.e("IBluetoothData interface is null");
                return;
            }
            loger.d("connecting bluetooth device................");
            int sdk = Build.VERSION.SDK_INT;
            if (sdk >= 10) {
                mSocket = mDevice.createInsecureRfcommSocketToServiceRecord(CONNECT_UUID);
            } else {
                mSocket = mDevice.createRfcommSocketToServiceRecord(CONNECT_UUID);
            }
            mSocket.connect();
            iInterface.connected(mDevice);
            isConnected = true;
            InputStream in = mSocket.getInputStream();
            out = mSocket.getOutputStream();
            String s = "";
            byte[] buffer = new byte[1024 * 3];
            int len;
            while((len = in.read(buffer)) > 0){
                s += new String(buffer, 0, len, "GBK");
                int index = -1;
                while ((index = s.indexOf("\r\n")) != -1) {
                    iInterface.receive(s.substring(0, index + 2));
                    s = s.substring(index + 2, s.length());
                    index = -1;
                }
            }
        } catch (IOException e) {
            loger.e("", e);
            iInterface.connectError();
        }finally{
            iInterface.disconnect(mDevice);
            isConnected = false;
        }
    }
    
    public void setInterface(IInterface iInterface) {
        this.iInterface = iInterface;
    }
    
    public boolean isConnected(){
        return isConnected;
    }

    public void write(byte[] buffer) {
        if (out != null) {
            try {
                out.write(buffer);
                out.flush();
            } catch (IOException e) {
                loger.e("write error", e);
            }
        }
    }

    public void close() {
        try {
            if (mSocket != null) {
                mSocket.close();
            }
        } catch (IOException e) {
            loger.e("close error", e);
        }
    }
}

搜索设备

        //首先动态注册广播
        IntentFilter filter = new IntentFilter();
        filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(receiver, filter);
//创建广播接收器
public BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device;
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                String address = device.getAddress();
                int state = device.getBondState();
                loger.d(String.format("found bluetooth device name=%s address=%s state=%s", name, address, state == BluetoothDevice.BOND_BONDED ? "BOND_BONDED" : "BOND_NONE"));
                if (!adapter.getDevices().contains(device)) {
                    adapter.addDevice(device);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                loger.d("select bluetooth device over!!!");
                if (mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.cancelDiscovery();
                }
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                case BluetoothDevice.BOND_BONDING:
                    loger.d("bluetooth device bonding....");
                    break;
                case BluetoothDevice.BOND_BONDED:
                    adapter.notifyDataSetChanged();
                    loger.d("bluetooth device bonded");
                    break;
                case BluetoothDevice.BOND_NONE:
                    loger.d("bluetooth device none!!!");
                    break;
                default:
                    break;
                }
            }
        }
    };

//配对方法
public boolean createBond(BluetoothDevice device) {
        try {
            Method createBondMethod = device.getClass().getMethod("createBond");
            return (Boolean) createBondMethod.invoke(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
点赞
收藏
评论区
推荐文章
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
春风化雨 春风化雨
1年前
Android File Transfer for mac(强大的安卓文件传输工具)
AndroidFileTransfer是一款适用于Mac计算机的应用程序,允许用户在其Mac和Android设备之间传输文件。要使用Android文件传输,您需要通过USB数据线将您的Android设备连接到您的Mac。建立连接后,您可以在Mac上打开An
Stella981 Stella981
2年前
Android app ADB命令
\查看设备adbdevicesps这个命令是查看当前连接的设备,连接到计算机的android设备或者模拟器将会列出显示若有多台安卓设备,可以通过在adb后面加上s<设备id对指定设备进行装包、卸载等操作\启动adbadbstartserver\关闭adbadbkillserver\安装软件
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
(绝对有用)iOS获取UUID,并使用keychain存储
UDID被弃用,使用UUID来作为设备的唯一标识。获取到UUID后,如果用NSUserDefaults存储,当程序被卸载后重装时,再获得的UUID和之前就不同了。使用keychain存储可以保证程序卸载重装时,UUID不变。但当刷机或者升级系统后,UUID还是会改变的。但这仍是目前为止最佳的解决办法了,如果有更好的解决办法,欢迎留言。(我整理的解决办法的参
Wesley13 Wesley13
2年前
Java基础入门
类别关键字说明访问控制private私有的protected受保护的public公共的类、方法和变量修饰符abstract声明抽象class类extends扩充,继承final最终值,不可改变的implements实现(接口)interface接口native本地
Stella981 Stella981
2年前
Android日志打印DebugLog
public class DebugLog{static String className;static String methodName;    private DebugLog(){        / Protect from instantiations /    
Stella981 Stella981
2年前
Linux应急响应(二):捕捉短连接
0x00前言​短连接(shortconnnection)是相对于长连接而言的概念,指的是在数据传送过程中,只在需要发送数据时,才去建立一个连接,数据发送完成后,则断开此连接,即每次连接只完成一项业务的发送。在系统维护中,一般很难去察觉,需要借助网络安全设备或者抓包分析,才能够去发现。0x01应急场景​
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究