標籤:android 藍芽 傳輸
今天學習了android藍芽方面的基礎知識,包含了開啟和關閉藍芽的操作,以及兩部手機之間通過藍芽實現的資料轉送。下面看代碼:
首先,需要在資訊清單檔裡添加藍芽操作的許可權:
<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
開啟藍芽的兩種方式:
第一種:Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
這種方式會提示使用者是否開啟藍芽
第二種:bluetoothAdapter.enable();
這種方式系統直接開啟藍芽
關閉藍芽的操作:bluetoothAdapter.disable();
搜尋附近藍芽的基本操作:
1.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//得到預設的藍芽適配器
2.if (bluetoothAdapter.isDiscovering()) {//如果正好在搜尋,則先取消搜尋
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
第二部在搜尋的時候,會發出一個廣播BluetoothDevice.ACTION_FOUND
3.建立並註冊BroadcastReceiver並在onReceive方法中進行操作,關鍵代碼如下:
@Overridepublic void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stubString action = arg1.getAction();//獲得已經搜尋到的藍牙裝置if (BluetoothDevice.ACTION_FOUND.equals(action)) {BluetoothDevice device = arg1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//搜尋到的裝置不是已經連結的裝置if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//將搜尋到的新藍牙裝置和名稱顯示到textview中show.append(device.getName()+":"+device.getAddress()+"\n");}}else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {//說明搜尋已經完成setProgressBarIndeterminateVisibility(false);setTitle("搜尋藍牙裝置");}}
2.兩個藍牙裝置之間的通訊
在資訊清單檔裡添加藍芽操作的許可權:
<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
A.在兩個手機上藍芽之間傳輸資料是通過BluetoothSocket和BluetoothServerSocket來實現的
B.建立BluetoothSocket和BluetoothServerSocket的方式如下:
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID);
serverSocket = bluetoothAdapter
.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
這裡需要注意的是:
UUID MY_UUID = UUID
.fromString("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c");
5dd231bf-d217-4e85-a26c-5e5cfda9aa0c是有系統提供的UUID.randomUUID().toString();產生的可以用於藍牙裝置之間的傳輸身份證,這個是唯一的
NAME是一個字串,是我們隨便給的
B.建立接受資料的線程類:
private class AcceptThread extends Thread{private BluetoothServerSocket serverSocket;private BluetoothSocket socket;private InputStream is;private OutputStream os;public AcceptThread() {//建立BluetoothServerSocket對象try {serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("name",UUID.fromString("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c"));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stub//等待接受藍芽用戶端的請求try {socket = serverSocket.accept();is = socket.getInputStream();os = socket.getOutputStream();while(true){byte[] buffer = new byte[128];int count = is.read(buffer);Message message = new Message();message.obj = new String(buffer,0, count, "utf-8");handler.sendMessage(message);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
得到已經綁定的藍牙裝置並用list顯示出來
luetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//得到預設的藍芽適配器C.Set<BluetoothDevice>paireDevices = bluetoothAdapter.getBondedDevices();//得到已經綁定的藍牙裝置if (paireDevices.size() > 0) {//若存在String []data = new String[paireDevices.size()];for (BluetoothDevice bluetoothDevice : paireDevices) {data[count++] = bluetoothDevice.getName()+":"+bluetoothDevice.getAddress();//得到綁定藍牙裝置的名稱和地址}adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,data);list.setAdapter(adapter);
為list的每一個清單項目綁定監聽事件:
list.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position,long id) {// TODO Auto-generated method stubString s = adapter.getItem(position);//獲得要串連的藍牙裝置的地址String address = s.substring(s.indexOf(":")+1).trim();if (null == device) {//獲得藍牙裝置,相當於網路用戶端制定的socketip地址device = bluetoothAdapter.getRemoteDevice(address);}if (null == clientSocket) {try {clientSocket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c"));//開始串連藍牙裝置clientSocket.connect();os = clientSocket.getOutputStream();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (null != os) {//向伺服器端發送一個字串try {os.write("這是另一台手機發送過來的資料".getBytes("utf-8"));Toast.makeText(MainActivity.this,"發送成功",1000);} catch (Exception e) {// TODO Auto-generated catch blockToast.makeText(MainActivity.this,"發送失敗",1000);e.printStackTrace();} }} }} );
分別將該應用部署到兩部手機,實現藍芽通訊.注意目前這種方式只支援簡單的資料轉送,如果需要出書二進位檔案,比如音頻,還是不可以的。
源碼下載
android通過藍芽實現兩台手機傳輸資料