我是Android新编码的新手。我一直在关注“专业Android 4应用程序开发”一书我基本上试图找出一种方法来接收任何设备发送的蓝牙串。这就是我到目前为止所拥有的
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the window layout
setContentView(R.layout.data);
ListView myData = (ListView)findViewById(R.id.list);
final ArrayList<String> mData = new ArrayList<String>();
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mData);
//Bind Array to List View
myData.setAdapter(aa);
startDiscovery();
String add = BluetoothDevice.EXTRA_DEVICE;
BluetoothDevice device = mAdapter.getRemoteDevice(add);
connectToServerSocket(device, MY_UUID);
mData.add(0, incoming);
aa.notifyDataSetChanged();
}
这是我的onCreate,这些是我不确定如何调用它们的类或函数...
private ArrayList<BluetoothDevice> deviceList =
new ArrayList<BluetoothDevice>();
private void startDiscovery() {
registerReceiver(discoveryResult,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
if (mAdapter.isEnabled() && !mAdapter.isDiscovering())
deviceList.clear();
mAdapter.startDiscovery();
}
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceList.add(remoteDevice);
Log.d(TAG, "Discovered" + remoteDeviceName);
}
};
这是我的插座:
private void connectToServerSocket(BluetoothDevice device, UUID uuid){
try{
BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
clientSocket.connect();
StringBuilder incoming = new StringBuilder();
listenforData(clientSocket, incoming);
transferSocket = clientSocket;
}catch(IOException e){
Log.e("BLUETOOTH","Bluetooth client I/O Exception", e);
}
}
我的数据听起来像这样:
private void listenforData(BluetoothSocket socket, StringBuilder incoming){
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try{
InputStream instream = socket.getInputStream();
int bytesRead = -1;
while(true){
bytesRead = instream.read(buffer);
if (bytesRead != -1){
String result = "";
while((bytesRead == bufferSize)&&(buffer[bufferSize-1]!=0)){
result = result + new String(buffer,0,bytesRead-1);
bytesRead= instream.read(buffer);
}
result = result + new String(buffer, 0, bytesRead -1);
incoming.append(result);
}
socket.close();
}
}catch (IOException e){
Log.e(TAG, "Message received failed.", e);
}
finally{
}
}}
我缺少的是如何从套接字侦听器中检索字符串并将它们放在ListView上。我需要一些指导。我是否正确地做到了这一点?