2014-02-09 43 views
0

嗨,任何人都知道爲什麼當我嘗試運行下面的代碼時,出現「無法在未調用Looper.prepare()的線程中創建處理程序」的錯誤?我在處理程序中添加了以便在程序位於while(true)循環內時從手機向遠程藍牙設備寫入消息。使用處理程序從Android向遠程藍牙設備寫入字節

public class ConnectedThread extends Thread{ 
     public final BluetoothSocket mmSocket; 
     public final InputStream mmInStream; 
     public final OutputStream mmOutStream; 

     private volatile Looper MyLooper; 

     public static final int message1 = 1; 
     public static final int message2 = 0; 

     //The Handler that gets information back from the Socket    
     public Handler mHandler = new Handler(){ 

      @Override 
      public void handleMessage(Message msg){ 
          Looper.prepare(); 

       switch(msg.what){ 
       case message1: 
           byte[] writeBuf = (byte[]) msg.obj; 
           String writeMessage = new String(writeBuf); 
           write(writeMessage); 
           break; 

       case message2: 
         byte[] readBuf = (byte[])msg.obj; 
           String readMessage = new String(readBuf); 
           write(readMessage); 
        break; 
        } 


      MyLooper = Looper.myLooper(); 
        Looper.loop(); 
        MyLooper.quit(); 
     } 
    }; 

     public ConnectedThread(BluetoothSocket socket){ 
      super(); 
      mmSocket = socket; 
      InputStream tmpIn = null; 
      OutputStream tmpOut = null; 

      try{ 
       tmpIn = socket.getInputStream(); 
       tmpOut=socket.getOutputStream(); 
      }catch(IOException e){ 
       e.printStackTrace(); 
      } 
      mmInStream = tmpIn; 
      mmOutStream = tmpOut; 
     } 

     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 (true) { 
       try { 
        if(mmInStream.available()>0) 
        { 
         try { 

          bytes = mmInStream.read(buffer); 
         } catch (IOException e) { 
          System.out.println("IO Exception occurred"); 
          e.printStackTrace(); 
          break; 
         } 
        } 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 

      //write to OutputStream 
      public void write(String message){ 
       byte[] msgBuffer = message.getBytes(); 
       try { 
        mmOutStream.write(msgBuffer); 
        mmOutStream.flush(); 
       } catch (IOException e) { 
        Log.d("Connected Thread", "...Error data send: " + e.getMessage() + "..."); 
        e.printStackTrace(); 
       } 
      } 

從另一個活動,我用「mHandler.sendMessage(m2);」向Handler發送消息以寫入遠程藍牙設備。但是,它不起作用,並出現上述錯誤。

回答

-2

我看到你試圖寫入字節,但你的功能write()String message,先修復它。

+0

你是什麼意思?即使我已轉換爲字節,仍然無法正常工作 –