蓝牙(4)通过蓝牙传输数据示例
这是一个通过蓝牙传输数据应用,需要两个设备都运行该应用
1 import java.io.InputStream; 2 import java.io.OutputStream; 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.Set; 6 import java.util.UUID; 7 8 import android.app.Activity; 9 import android.bluetooth.BluetoothAdapter; 10 import android.bluetooth.BluetoothDevice; 11 import android.bluetooth.BluetoothServerSocket; 12 import android.bluetooth.BluetoothSocket; 13 import android.content.BroadcastReceiver; 14 import android.content.Context; 15 import android.content.Intent; 16 import android.content.IntentFilter; 17 import android.os.Bundle; 18 import android.os.Handler; 19 import android.os.Message; 20 import android.view.View; 21 import android.view.Window; 22 import android.widget.AdapterView; 23 import android.widget.AdapterView.OnItemClickListener; 24 import android.widget.ArrayAdapter; 25 import android.widget.ListView; 26 import android.widget.Toast; 27 28 /* 29 * 这是一个通过蓝牙传输数据的android应用 30 * 主要功能如下: 31 * 搜索蓝牙设备, 32 * 与其中一个蓝牙设备配对 33 * 向它发送一个文本数据 34 * 接收数据并显示 35 * 36 * 本例子中包括用蓝牙收发数据的客户端,服务端 37 */ 38 public class Main extends Activity implements OnItemClickListener { 39 40 //搜索蓝牙设备第1步,在manifest中添加权限 41 42 //搜索蓝牙设备第2步,准备相关成员变量 43 //用于搜索 44 private BluetoothAdapter bluetoothAdapter; 45 46 //用于保存蓝牙设备. 47 private ListView lvDevices; 48 private List<String> bluetoothDevices = new ArrayList<String>(); 49 private ArrayAdapter<String> arrayAdapter; 50 51 //蓝牙设备的uuid 相当于port 52 private final UUID MY_UUID = UUID.fromString("db764ac8-2d1c-2e56-23fe-59d03c27bae3"); 53 private final String NAME = "Bluetooth_Socket"; 54 55 //用于sokcet读写数据 56 private BluetoothSocket clientSocket; 57 private BluetoothDevice device; 58 private AcceptThread acceptThread; 59 private OutputStream os; 60 61 @Override 62 public void onCreate(Bundle savedInstanceState) { 63 super.onCreate(savedInstanceState); 64 65 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 66 setContentView(R.layout.main); 67 68 //搜索蓝牙设备第3步,得到BluetoothAdapter 69 bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 70 71 //搜索蓝牙设备第4步,找出已经配对的设备 72 Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); 73 if (pairedDevices.size() > 0) { 74 for (BluetoothDevice device : pairedDevices) { 75 bluetoothDevices.add("蓝牙设备名:" + device.getName() + " 蓝牙地址:" + device.getAddress() + "\n"); 76 } 77 } 78 79 //搜索蓝牙设备第5步,注册搜索设备接收广播 80 //找到设备 81 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 82 this.registerReceiver(receiver, filter); 83 //搜索完成 84 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 85 this.registerReceiver(receiver, filter); 86 87 //启动蓝牙socket服务端 88 acceptThread = new AcceptThread(); 89 acceptThread.start(); 90 91 //listview相关 92 lvDevices = (ListView) findViewById(R.id.lvDevices); 93 arrayAdapter = new ArrayAdapter<String>(this, 94 android.R.layout.simple_list_item_1, android.R.id.text1, 95 bluetoothDevices); 96 lvDevices.setAdapter(arrayAdapter); 97 lvDevices.setOnItemClickListener(this); 98 99 } 100 101 //搜索蓝牙设备第6步,开始搜索设备 102 public void onClick_Search(View view) { 103 //设置滚动圈 104 setProgressBarIndeterminateVisibility(true); 105 setTitle("正在搜索..."); 106 //如正在搜索,要先取消. 107 if (bluetoothAdapter.isDiscovering()) { 108 bluetoothAdapter.cancelDiscovery(); 109 } 110 bluetoothAdapter.startDiscovery(); 111 } 112 //搜索蓝牙设备第7步,搜索到设备的广播处理. 113 private final BroadcastReceiver receiver = new BroadcastReceiver() { 114 @Override 115 public void onReceive(Context context, Intent intent) { 116 String action = intent.getAction(); 117 118 if (BluetoothDevice.ACTION_FOUND.equals(action)) { 119 120 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 121 if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 122 bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "\n"); 123 arrayAdapter.notifyDataSetChanged(); 124 } 125 } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED 126 .equals(action)) { 127 setProgressBarIndeterminateVisibility(false); 128 setTitle("选择要配对的蓝牙设备"); 129 } 130 } 131 }; 132 133 /* 134 * 蓝牙收发数据客户端代码 135 * 136 */ 137 @Override 138 public void onItemClick(AdapterView<?> parent, View view, int position,long id) { 139 String s = arrayAdapter.getItem(position); 140 //蓝牙客户端发数据第1步,得到设备的地址. 141 String address = s.substring(s.indexOf(":") + 1).trim(); 142 143 try { 144 //如果正在搜索,要先取消. 145 if (bluetoothAdapter.isDiscovering()) { 146 bluetoothAdapter.cancelDiscovery(); 147 } 148 try { 149 //蓝牙客户端发数据第2步,得到设备 150 if (device == null) { 151 device = bluetoothAdapter.getRemoteDevice(address); 152 153 } 154 if (clientSocket == null) { 155 //蓝牙客户端发数据第3步,构造客户端socket 156 clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID); 157 //蓝牙客户端发数据第4步,开始连接 158 clientSocket.connect(); 159 160 //蓝牙客户端发数据第5步,得到数据流.若流不容,则成功连接 161 os = clientSocket.getOutputStream(); 162 163 } 164 } catch (Exception e) { 165 } 166 if (os != null) { 167 //蓝牙客户端发数据第6步,发送数据. 168 os.write("发送信息到其他蓝牙设备".getBytes("utf-8")); 169 } 170 } catch (Exception e) { 171 } 172 } 173 174 175 /* 176 * 蓝牙收发数据服务端代码 177 */ 178 //要用Handler向ui线程发送要显示的数据. 179 private Handler handler = new Handler() { 180 public void handleMessage(Message msg) { 181 super.handleMessage(msg); 182 Toast.makeText(Main.this, String.valueOf(msg.obj),Toast.LENGTH_LONG).show(); 183 } 184 }; 185 //下面是蓝牙服务器类 186 private class AcceptThread extends Thread { 187 188 //蓝牙服务端 第1步,准备相关成员. 189 //监听socket 190 private BluetoothServerSocket serverSocket; 191 //读写socket 192 private BluetoothSocket socket; 193 //读写流 194 private InputStream is; 195 private OutputStream os; 196 197 public AcceptThread() { 198 try { 199 //蓝牙服务端 第2步,构造监听socket 200 serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); 201 } catch (Exception e) { 202 } 203 } 204 public void run() { 205 try { 206 //蓝牙服务端 第3步,开始监听. 207 socket = serverSocket.accept();//没有客户连接时,会阻塞在这里.一直监听. 208 //蓝牙服务端 第4步,如有连接,那么得到读写socket,然后得到读写流. 209 is = socket.getInputStream(); 210 os = socket.getOutputStream(); 211 212 byte buffer [] = new byte[128]; 213 while (true) { 214 //蓝牙服务端 第5步,读数据. 215 int count = is.read(buffer); 216 217 //蓝牙服务端 第6步,把读到的数据发送到UI线程. 218 Message msg = new Message(); 219 msg.obj = new String(buffer, 0, count, "utf-8"); 220 handler.sendMessage(msg); 221 } 222 } catch (Exception e) { 223 } 224 } 225 } 226 }