所以我創建了一個應用程序,其中有一個GUI類。此應用程序將偵聽來自另一個應用程序的2個傳入字符串,這些應用程序是在觸發togglebutton時創建的我簡直無法將我的頭包裹起來,就是如何讀取傳入的字節,並將它們通過我的代碼傳回到它們在GUI類中使用的位置。希望任何人都能夠提供幫助。在我的Android應用程序中使用讀取方法
當我發送我的兩個字符串時,我得到了兩個字節,然後發送第一個字節,獲取「%」字符串的字節,將其作爲分隔符發送,然後發送第二個字節。
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;
}
}
太多的代碼:) –
呵呵我知道這可能是有點過分,但有一個很難看到在哪裏我應該減少 – Drakthal