我无法在Android中取消我的主题

时间:2014-12-17 19:03:37

标签: android multithreading bluetooth

我正在开发一个通过蓝牙与Arduino通信的应用程序,但是,我不知道为什么我无法取消负责蓝牙输入流的线程。

public class mainclass extends Activity{
 BluetoothSocket scSocket = AnotherClass.btSocket;
 SendReceiveBytes  sendReceiveBT;
 Thread th;

 protected void onCreate(Bundle savedInstanceState) {
         .
         .
         sendReceiveBT = new SendReceiveBytes(scSocket);
         th = new Thread(sendReceiveBT);
         th.start();
         .
         .
         sendReceiveBT.stop=true;
         Log.e(TAG, "Request sent");
         .
         .
       }
 }

public class SendReceiveBytes implements Runnable {
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";

 private  BluetoothSocket btSocket;
 private InputStream btInputStream = null;
 private OutputStream btOutputStream = null;
 public boolean stop=false;
 public boolean stopped=false;
 String TAG = "SendReceiveBytes";

 public SendReceiveBytes(BluetoothSocket socket) {
 btSocket = socket;
 try {
 btInputStream = btSocket.getInputStream();
 btOutputStream = btSocket.getOutputStream();
 } 
 catch (IOException streamError) { 
 Log.e(TAG, "Error when getting input or output Stream");
 }
 }

 public void run() {
 byte[] buffer = new byte[1024]; // buffer store for the stream
 int bytes; // bytes returned from read()

 // Keep listening to the InputStream until an exception occurs
 while (!stop) {
 try {
 // Read from the InputStream
 bytes = btInputStream.read(buffer);
 // Send the obtained bytes to the UI activity
 byte[] readBuf = (byte[]) buffer;
 // construct a string from the valid bytes in the buffer
 readMessage = new String(readBuf, 0, bytes);
 } 
 catch (IOException e) {
 Log.e(TAG, "Error reading from btInputStream");
 break;
 }
 }
 Log.e(TAG, "Quit");
 stopped=true;
 }

}

在LogCat中,带有"请求发送的标签"显示这意味着我已经设置了"停止"然而,标签为" Quit"永远不会出现。

1 个答案:

答案 0 :(得分:0)

您可以尝试覆盖stop() - 方法,该方法将stop-flag设置为true。还要确保关闭你的溪流。