所以我创建了一个应用程序,其中有一个 GUI 类。此应用程序将在激活切换按钮时侦听来自我创建的另一个应用程序的 2 个传入字符串。我根本无法理解的是如何读取传入的字节并将它们通过我的代码传递回它们在我的 GUI 类中使用的位置。希望任何人都能够提供帮助。
当我发送我的两个字符串时,我得到两个字符串的字节,然后发送第一个,获取“%”字符串的字节,将其作为分隔符发送,然后发送第二个。
public void ListenForAddress(View view)
{
on = ((ToggleButton) view).isChecked();
if(on)
{
Address address = reciever.RecieveObject();
Intent intent = new Intent(this, Screen3.class);
String adressStr = address.Address;
intent.putExtra("ADRESS_MESSAGE", adressStr);
String postalcodeStr = address.Postalcode;
intent.putExtra("POSTALCODE_MESSAGE", postalcodeStr);
intent.putExtra("ONE", 1);
startActivity(intent);
}
else
{
reciever.closeReception();
}
}
如您所见,我创建了一个接收器,并调用了一个名为 RecieveObject() 的方法,该方法如下所示。
public Address RecieveObject()
{
accThread = new AcceptThread();
accThread.start();
return null;
}
下一步是创建连接并启动管理线程的线程
public class AcceptThread extends Thread {
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("Server", MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
mConnSock = new manageConnectedSocket(socket);
mConnSock.read();
try {
mmServerSocket.close();
} catch (IOException e) {
}
break;
}
}
}
}
最后一步是处理数据的线程
public class manageConnectedSocket extends Thread {
public manageConnectedSocket(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
public Address read() {
byte[] buffer = new byte[1024];
int bytes;
Address address = new Address("", "");
int count = 0;
while(count<2)
{
try {
bytes = mmInStream.read(buffer);
if(count==0)
{
address.Address = new String(buffer);
}
else
{
address.Postalcode = new String(buffer);
}
buffer = new byte[1024];
} catch (IOException e) {
break;
}
}
return address;
}
}