[英]How to use Connected Thread in multiple activites
我是Android的新手。 首先,我編寫了一個應用程序,該應用程序通過藍牙連接到另一台設備,然后使用套接字和連接的線程發送和接收數據。 使用一項活動時,一切工作正常,我使用處理程序接收數據。 然后,我開始制作具有多個活動的應用程序,因此為套接字連接和連接線程創建了一個特殊的類。 我通常從任何活動發送數據,但我不知道如何接收答案(如何在許多活動中創建處理程序,或使用什么替代方法)。 您能幫我寫這行代碼嗎,我應該補充一下。
謝謝。
這是我的主題:
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e) {}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
while(true) {
try {
bytes = mmInStream.read(buffer);
byte[] readBuf = (byte[]) buffer;
String strIncom = new String(readBuf, 0, bytes);
// Here I need some method to send data to activity
}
catch (IOException e) {
break;
}
}
}
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
}
}
}
好吧,您可以做的一件事就是使用Interface
,
例如:
public class ConnectedThread extends Thread {
// You declare your interface in the Class body
public static interface CallBackListener
{
public void onReceived(String msg);
}
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private CallBackListener listener = null;
// then, those who want to use this class must implement
// this interface
public ConnectedThread(BluetoothSocket socket, CallBackListener aListener)
{
this.listener = aListener;
...
在線程的run方法中,您可以這樣做:
// Here I need some method to send data to activity
if (listener != null)
{
listener.onReceived(strIncom);
}
創建類時,請執行以下操作:
BluetoothSocket socket = null;
/*
* Create the BlueToothSocket here
BluetoothSocket socket = new BluetoothSocket(...);
*/
ConnectedThread conThread = new ConnectedThread(socket, new ConnectedThread.CallBackListener()
{
@Override
public void onReceived(String msg)
{
// here you'll receive the string msg
// keep in mind that you receive this call
// in the ConnectedThread's context, not the UI thread
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.