2013-06-19 44 views
1

所以我对Java很新,所以要温柔。 我想通过蓝牙连接两部手机。我创建了一个套接字,但我应该如何使用它?我的意思是,蓝牙教程说我应该调用public void write(byte [] bytes)来发送数据,但是如何?我创建了按钮,分配了“onClick”方法,但是什么呢?我应该如何调用ConnectedThread窗体UI线程中的方法?下面是来自教程 的示例私有类ConnectedThread extends Thread最终的BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream;如何调用线程方法

public ConnectedThread(BluetoothSocket socket) { 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 
     Message msg = mainHandler.obtainMessage(); 
     Bundle bundle = new Bundle(); 
     String btnTxt = "Socket aquizaired"; 
     bundle.putString("myKey", btnTxt); 
     msg.setData(bundle); 
     mainHandler.sendMessage(msg); 
     // Get the input and output streams, using temp objects because 
     // member streams are final 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 

     } catch (IOException e) { } 

     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 { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 
       // Send the obtained bytes to the UI activity 
       // mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget(); 
      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

    /* Call this from the main activity to send data to the remote device */ 
    public void write(byte[] bytes) { 
     try { 
      mmOutStream.write(bytes); 
     } catch (IOException e) { } 
    } 

    /* Call this from the main activity to shutdown the connection */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

,并在UI线程我有类似的财产以后

private void sendSms(){ // method assigned to button "onClick" 
    // i want to send some text here, like "hello" or something... 
    //??????????????????????????? 
} 
+0

您需要创建一个线程并将参数传递给SendSms – Charlie

回答

0

在Android SDK的例子有一个很好的蓝牙聊天例如,你应该看看它。

public void write(byte[] out) { 
    ConnectedThread r; 
    synchronized (this) { 
     if (mState != STATE_CONNECTED) return; 
     r = mConnectedThread; 
    } 
    r.write(out); 
}