andriod与蓝牙串口编程(一)

最近在做一个关于蓝牙串口的小工具,本人使用的蓝牙是4.0(不是低功耗蓝牙),Android 最低版本是4.3。这其中当然有各种原因了。在做蓝牙编程你必须我一部Android4.3版本以上的带蓝牙的安卓手机和一个能连接电脑的蓝牙和一个串口工具下载地址http://download.csdn.net/detail/u010955636/9583641

1.写界面加权限

这一部分没啥说的都不一样根据自己的需求。
权限就两个开发蓝牙必须的:
  	
        

2 开始开发蓝牙

我们在手机蓝牙串口开发中 ,手机是做为客户端只需要写客户端的代码就行了;
  class ConnectThread extends Thread {
        // private final BluetoothSocket mmSocket;
        private BluetoothDevice device;
        public ConnectThread(BluetoothDevice device) {
            this.device = device;
        }
        public void run() {
            BluetoothSocket tmp = null;
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                tmp.connect();
                socket=tmp;
                new ClientManageThread(tmp).start();
            } catch (IOException e) {
                try {
                    tmp = (BluetoothSocket) device
                            .getClass()
                            .getMethod("createRfcommSocket",
                                    new Class[] { int.class })
                            .invoke(device, 1);
                    tmp.connect();
                    socket=tmp;
                    new ClientManageThread(tmp).start();
                } catch (Exception e1) {
                    e1.printStackTrace();
                    try {
                            tmp.close();
                    } catch (IOException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
                    }
                }
            }

        }
    }

    //作为客户端发送数据
    class ClientManageThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final OutputStream mmOutStream;
        private final InputStream mmInputStream;
        public ClientManageThread(BluetoothSocket socket) {
            mmSocket = socket;
            OutputStream tmpOut = null;
            InputStream tmpIn = null;
            try {
                tmpOut = socket.getOutputStream();
                tmpIn = socket.getInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mmOutStream = tmpOut;
            mmInputStream = tmpIn;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();
            byte[] buffer = new byte[1024];
            int len = -1;
            while (true) {
                try {
                    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
                   // while ((len = mmInputStream.read(buffer)) != -1) {
                    len = mmInputStream.read(buffer);
                        outSteam.write(buffer, 0, len);
                 //  }
                    mHandler.obtainMessage(0, outSteam).sendToTarget();
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
            if (mmOutStream != null) {
                String str="11";
                try {
                    mmOutStream.write(str.getBytes());
                    mmOutStream.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        if (false) {
                            mmOutStream.close();
                            mmSocket.close();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }}
             /* Call this from the main activity to send data to the remote device */
        }

    public void write(String s) {
        try {
            OutputStream mmOutStream=socket.getOutputStream();
            byte[] bytes=s.getBytes();
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) { }
    }
}
这几行代码就是Android蓝牙开发的核心代码,只要根据需要在改改就可以了。

3蓝牙列表

public class BluetoothListActivity extends Activity implements AdapterView.OnItemClickListener {
    private static final String TAG = BluetoothListActivity.class.getSimpleName();

    private BluetoothAdapter mBluetoothAdapter;
    private List devices = new ArrayList();
    private ListView deviceListView;
    private DeviceAdapter adapter;
    private Button bt_search;
    private TextView tv_view;
    private ImageView iv_back;
    private Handler handler = new Handler();
    private BluetoothDevice device;
    private  ProgressDialog  progressDialog;

    /* Discovery is Finished */



    private final BroadcastReceiver dicoverReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!containsDevice(device)) {
                    devices.add(device);
                    if (adapter != null)
                        adapter.notifyDataSetChanged();
                }
            }
        }
    };






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fragment_main);
        progressDialog=new ProgressDialog(BluetoothListActivity.this);
        progressDialog.setTitle("搜索蓝牙");
        progressDialog.setMessage("搜索设备中...");
        progressDialog.setCancelable(true);

        initTitleClick();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(dicoverReceiver, filter);
        initBlueTooth();
        initView();
        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Register the BroadcastReceiver
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                registerReceiver(dicoverReceiver, filter); // Don't forget to unregister during onDestroy
                mBluetoothAdapter.startDiscovery();// 开始扫描

              //  adapter.notifyDataSetChanged();
              // new SearchBluetoothTask().execute();

            }
        });
    }



    private void initBlueTooth() {
        // TODO Auto-generated method stub
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // 设备不支持蓝牙功能
            Log.i("EF-BTBee", ">>BTBee is disable!");
            finish();
            return;
        } else {
            if (!mBluetoothAdapter.isEnabled()) {// 蓝牙处于关闭状态
                Intent enableBtIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 0);
            }
            Set pairedDevices = mBluetoothAdapter
                    .getBondedDevices();// 获取本机已配对设备
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    if (!containsDevice(device))
                        devices.add(device);
                }
            }
            mBluetoothAdapter.startDiscovery();// 开始扫描
        }
    }

    private void initTitleClick(){
        iv_back= (ImageView) findViewById(R.id.iv_back);
        tv_view= (TextView) findViewById(R.id.tv_state);
        tv_view.setText("选择一个设备进行连接");
        bt_search= (Button) findViewById(R.id.bt_isconnect);
        bt_search.setText("搜索");
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    private boolean containsDevice(BluetoothDevice device) {
        for (BluetoothDevice dev : devices)
            if (dev.getAddress().equals(device.getAddress()))
                return true;
        return false;
    }

    private void initView() {
        // TODO Auto-generated method stub
        deviceListView = (ListView) findViewById(R.id.deviceList);
        adapter = new DeviceAdapter(this);
        showDevices();
    }
    protected void showDevices() {
        if (devices.size()>0){
             adapter.setDevices(devices);
             deviceListView.setAdapter(adapter);
             deviceListView.setOnItemClickListener(this);}
        else {
            Toast.makeText(getApplicationContext(),"没有检测到蓝牙",Toast.LENGTH_SHORT);
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(dicoverReceiver);
        mBluetoothAdapter.cancelDiscovery();
    }
    @Override
    public void onItemClick(AdapterView parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        device= devices.get(position);
        Intent intent=new Intent(BluetoothListActivity.this,BluetoothActivity.class);
        intent = intent.putExtra("device",device);
         startActivity(intent);
        finish();
    }


    public class SearchBluetoothTask extends AsyncTask> {

        @Override
        protected List doInBackground(Void... voids) {
            // Create a BroadcastReceiver for ACTION_FOUND
            final List devices1 = new ArrayList();
            final BroadcastReceiver mReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    // When discovery finds a device
                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                        // Get the BluetoothDevice object from the Intent
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        // Add the name and address to an array adapter to show in a ListView
                        devices1.add(device);
                    }
                }
            };

            IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(dicoverReceiver, filter1); // Don't forget to unregister during onDestroy
            adapter.notifyDataSetChanged();

            return devices1;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();

        }

        @Override
        protected void onPostExecute(List bluetoothDevices) {
            super.onPostExecute(bluetoothDevices);
            progressDialog.dismiss();

            Toast.makeText(getApplicationContext(),bluetoothDevices.get(0).getName(),Toast.LENGTH_SHORT);
        }
    }
}

4总结

  总体而言Android 蓝牙串口开发从功能实现上还是比较简单的,但是还是有很多在应用中的坑等着你去踩,只有经历才会明白的。未完待续。。。

你可能感兴趣的:(Android)