【发布时间】:2014-10-02 23:20:18
【问题描述】:
我正在制作一个基于 Bluetooth 的文件传输应用程序,但我不确定如何在此处使用 Threads。
当我开始在应用程序的服务器部分侦听传入连接时工作正常,但我用来执行此任务且不阻塞 UI 的线程在被调用后没有返回到主 Activity。以下是部分代码:
public class AcceptThread extends Thread {
private BluetoothServerSocket mmServerSocket;
public BluetoothSocket mmBlueToothSocket;
private final BluetoothAdapter mmBluetoothAdapter;
/*Accept incomming connections on the server*/
public AcceptThread(BluetoothAdapter mBluetoothAdapter){
BluetoothServerSocket tmp = null;
this.mmBluetoothAdapter = mBluetoothAdapter;
//works well
try {
this.mmServerSocket = mmBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(BluetoothConfig.mServiceName,BluetoothConfig.mUUID);
} catch (IOException e) {
mmServerSocket = tmp;
Log.d("AcceptThreadConstructorErr:", e.getMessage());
}
}
public void run(){
//while (true){
try {
mmBlueToothSocket = this.mmServerSocket.accept();
Log.d("AcceptThreadRun:", "mmServerSocket reached");
} catch (IOException e) {
Log.d("AcceptThreadRunErr:", e.getMessage());
//break;
}
//}
//If I call the ConnectedThread part of the code here it raises an error so I am trying to call it from my Activity but is not returning there after executing the run part of this class
}//run
}//AcceptThread class
public class MainActivity extends Activity {
private BluetoothServerSocket mmServerSocket;
public BluetoothSocket mmBlueToothSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//accept to listen for incomming connections
AcceptThread acceptThread = new AcceptThread(bConfig.getBluetoothAdapter());
acceptThread.start();
//After the start execution this part is never reached!!
connectedThread();
}
//Called from acceptThread once innitiated the connections listening in AcceptThread
public void connectedThread(){
socket = acceptThread.mmBlueToothSocket;
if (socket == null){
Log.d("acceptThread:", "socket Null in acceptThread");
}
if (socket != null){
try {
ConnectedThread connected = new ConnectedThread(socket);
connected.start();
Log.d("serverConnect", "connect.start() ok");
}catch (Exception e) {
Log.d("serverConnect:", e.getMessage());
}
}
}//connectedThread
}//Activity
您能否告诉我,我缺少 Thread 实现的哪个组件(可能是 Handler?),才能访问 ConnectedThread 部分并使其工作?似乎没有错误,只是线程退出并没有返回调用者活动。
谢谢
【问题讨论】:
-
acceptThread.start() 在什么函数中被调用?您已将调用置于静态上下文中?
-
@nandeesh,正在调用activity,看最后一段代码sn-p。
标签: java android multithreading bluetooth file-transfer