安卓与51单片机的蓝牙通信(安卓端)

之前看到网上的一些代码写得比较复杂,初学者看起来大概会很吃力,然后就有了这篇!
//大概会比较好懂一点。
本篇只要是实现与51单片机的通信功能,所以我想要尽量的简化一下。

话不多说上代码!
//先是ui线程的部分 这部分主意是监听控件 蓝牙的连接需要单独写一个线程
//此部分代码只是截取 缺少的部分都可以脑补的出来。。
private Button connect;
private ConnectThreads connectThreads;//用于连接的线程
private BluetoothDevice bluetoothDevice;
private BluetoothAdapter bluetoothAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    connect = (Button) findViewById(R.id.button);
    //此处省略了很多控件的实例化

    //点击连接按钮之后 
    //此代码需要自己事先开启蓝牙并配对好蓝牙
connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //实例化BluetoothAdapter
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            //getBondedDevices()是得到你手机所以已经配对过的设备
            Set pairedDevices = bluetoothAdapter.getBondedDevices();
            for (BluetoothDevice device : pairedDevices) {
                //循环把你最后一个配对的设备传给bluetoothDevice
                bluetoothDevice = device;
            }
            //开启连接线程
            connectThreads = new ConnectThreads(handler, bluetoothDevice);
            connectThreads.start();
        }
    });
    //发送按钮
send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
                Message msg = new Message();
                msg.what = 0x001;
                Bundle bundle = new Bundle();
                bundle.putString("消息", editText.getText().toString());
                msg.setData(bundle);
                connectThreads.handler.sendMessage(msg);
                //在自己定义的listview中显示出来
                list.add(editText.getText().toString() + "  已发送");
                //刷新listview
                arrayAdapter.notifyDataSetChanged();
        }
    });

}

//用于传给子线程要传输的文本
public void send() {
    Message msg = new Message();
    msg.what = 0x001;
    Bundle bundle = new Bundle();
    //command是自己定义的String
    String command = editText.getText().toString();
    bundle.putString("消息", command);
    msg.setData(bundle);
    connectThreads.handler.sendMessage(msg);
}

//用于接收子线程传来的信息
Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        //处理消息
        switch (msg.what) {
            case 0x01:
                list.add("蓝牙连接成功");
                arrayAdapter.notifyDataSetChanged();
                break;
            case 0x00:
                list.add(" 单片机:" + msg.obj.toString());
                arrayAdapter.notifyDataSetChanged();
                break;
        }
        super.handleMessage(msg);
    }
};

//ui的线程大概就是这样 这样用起来会有这样那样的不方便 需要大家自己再慢慢改进调整了。
//下面是负责蓝牙连接和发送的线程

public class ConnectThreads extends Thread{
private BluetoothDevice bluetoothDevice;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket socket;
public Handler handler;
private OutputStream outStream; 
//用于单片机的固定uuid
public final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

public  ConnectThreads(Handler handler,BluetoothDevice bluetoothDevice){
    this.bluetoothDevice = bluetoothDevice;
    this.handler = handler;
}

@Override
public void run() {
    try {
        //就像socket通信中的client一样
        socket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
        //如果蓝牙还在扫描设备 就停止扫描
        if (bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        //BluetoothSocket连接
        socket.connect();
        //发送一个空的msg表示连接成功
        Message msg = handler.obtainMessage();
        msg.what = 0x01;
        msg.obj = "";
        msg.sendToTarget();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //开启一个新的线程用于接收单片机传过来的信息
    ReceiveThread receiveThread = new ReceiveThread(handler,socket);
    receiveThread.start();
    //接收主线程发过来的发送内容
    Looper.prepare();
    handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0x001){
                try {
                    outStream = socket.getOutputStream();
                    outStream.write(msg.getData().get("消息").toString().getBytes());
                    outStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    Looper.loop();
}

}

//因为需要不断的循环接收发过来的信息
//负责接受的部分也要单独写一个线程

public class ReceiveThread extends Thread{
private Handler handler;
private BluetoothSocket socket;
private BufferedReader bufferedReader;
public ReceiveThread(Handler handler,BluetoothSocket socket){
this.handler = handler;
this.socket = socket;
}

@Override
public void run() {

        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String obj = null;
    try {
        while ((obj = bufferedReader.readLine())!=null){
            //发送成功读取到对象的消息,消息的obj参数为读取到的对象
            Message msg = handler.obtainMessage();
            msg.what = 0x00;
            msg.obj = obj;
            msg.sendToTarget();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

这样就全部结束了 第一次写博客 希望给看各位官带来帮助。

你可能感兴趣的:(移动开发)