简洁的连接蓝牙串口BC04的代码

网上好多代码都在搞什么自动配对,搞的好复杂,其实实际应用没有必要的,只要把Android当作主机,主动配对蓝牙串口保存下来,然后根据蓝牙的地址进行连接并收发消息

其实蓝牙配对其实就好比手机选择wifi热点输入密码一样,平时应用有必要自动配对吗?



package com.example.zmy.bluetoothserialnew;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class MainActivity extends ActionBarActivity {

    String macAddress = "";
    boolean connecting = false;
    boolean connected = false;
    int     connetTime = 0;

    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothDevice mBluetoothDevice = null;
    private BluetoothSocket socket = null;

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //@Override
    public void OnButtonClick(View v)
    {
        Log.i("info", "OnButtonclick....");

        ConnectThread blueThread = new ConnectThread("00:06:71:00:40:16");
        blueThread.start();
    }

    public void OnButtonSendClick(View v)
    {
        sendMessage(socket, "comfrom android cell  phone....");
    }

    //----------------------------------------------------------------------------------------

    private class ConnectThread extends Thread {


        public ConnectThread(String mac) {
            macAddress = mac;
        }

        public void run() {
            connecting = true;
            connected = false;
            if(mBluetoothAdapter == null){
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            }
            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
            Log.i("info", "device is:" + mBluetoothDevice);
            mBluetoothAdapter.cancelDiscovery();
            initSocket();
            //adapter.cancelDiscovery();
            while (!connected && connetTime <= 10) {
                try {
                    socket.connect();
                    connected = true;
                } catch (IOException e1) {
                    connetTime++;
                    connected = false;
                    // 关闭 socket
                    try {
                        socket.close();
                        socket = null;
                    } catch (IOException e2) {
                        //TODO: handle exception
                        Log.e("exception", "Socket", e2);
                    }
                } finally {
                    connecting = false;
                }
                //connectDevice();
            }
            // 重置ConnectThread
            //synchronized (BluetoothService.this) {
            //ConnectThread = null;
            //}

            BluetoothSocketListener bluetoothListener = new BluetoothSocketListener(socket);
            bluetoothListener.run();
        }

        public void cancel() {
            try {
                socket.close();
                socket = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connecting = false;
            }
        }

        /**
         * 取得BluetoothSocket
         */
        private void initSocket() {
            BluetoothSocket temp = null;
            try {
                Method m = mBluetoothDevice.getClass().getMethod(
                        "createRfcommSocket", new Class[] { int.class });
                temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//这里端口为1
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            socket = temp;
        }
    }

    private void sendMessage(BluetoothSocket socket, String msg) {
        //OutputStream outStream;
        try {
            //outStream = socket.getOutputStream();
            PrintWriter outStream = new PrintWriter(socket.getOutputStream(),true);
            byte[] byteString = (msg + " ").getBytes();
            byteString[byteString.length - 1] = 0;
            //outStream.write(byteString);
            outStream.write(msg);
            outStream.flush();
            Log.i("info", "sendmessage:" + msg + "....................");
        } catch (IOException e) {
            Log.i("BLUETOOTH_COMMS", e.getMessage());
        }
    }

    private class BluetoothSocketListener implements Runnable {

        private BluetoothSocket socket;
        //private TextView textView;
        //private Handler handler;

        public BluetoothSocketListener(BluetoothSocket socket) {
            this.socket = socket;
        }

        public void run() {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            try {
                InputStream instream = socket.getInputStream();
                int bytesRead = -1;
                String message = "";
                while (true) {
                    message = "";
                    bytesRead = instream.read(buffer);
                    if (bytesRead != -1) {
                        while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
                            message = message + new String(buffer, 0, bytesRead);
                            bytesRead = instream.read(buffer);
                        }
                        message = message + new String(buffer, 0, bytesRead);
                        Log.i("msg", message);
                        //handler.post(new MessagePoster(textView, message));
                        //JniTestHelper.sendToUI(message);
                        socket.getInputStream();
                    }
                }
            } catch (IOException e) {
                Log.d("BLUETOOTH_COMMS", e.getMessage());
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值