2012-11-19 69 views
24

我是android新手。我正在設計一個android應用程序,通過藍牙從硬件設備接收串行數據。我正在研究Htc願望S.我使用示例藍牙聊天代碼來接收數據。但收到的數據不正確。它錯過了一些價值。任何人都可以提供我任何其他示例代碼,通過藍牙接收大量數據並將其保存在文件中。如何使用android藍牙接收串行數據

+0

我需要團結類似:-( – mindmyweb

回答

54

試試這個代碼:

活動:

package Android.Arduino.Bluetooth; 
import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.Intent; 
import android.os.Bundle; 
import android.os.Handler; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.EditText; 
import android.widget.Button; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Set; 
import java.util.UUID; 

public class MainActivity extends Activity 
{ 
TextView myLabel; 
EditText myTextbox; 
BluetoothAdapter mBluetoothAdapter; 
BluetoothSocket mmSocket; 
BluetoothDevice mmDevice; 
OutputStream mmOutputStream; 
InputStream mmInputStream; 
Thread workerThread; 
byte[] readBuffer; 
int readBufferPosition; 
int counter; 
volatile boolean stopWorker; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Button openButton = (Button)findViewById(R.id.open); 
    Button sendButton = (Button)findViewById(R.id.send); 
    Button closeButton = (Button)findViewById(R.id.close); 
    myLabel = (TextView)findViewById(R.id.label); 
    myTextbox = (EditText)findViewById(R.id.entry); 

    //Open Button 
    openButton.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      try 
      { 
       findBT(); 
       openBT(); 
      } 
      catch (IOException ex) { } 
     } 
    }); 

    //Send Button 
    sendButton.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      try 
      { 
       sendData(); 
      } 
      catch (IOException ex) { } 
     } 
    }); 

    //Close button 
    closeButton.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      try 
      { 
       closeBT(); 
      } 
      catch (IOException ex) { } 
     } 
    }); 
} 

void findBT() 
{ 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if(mBluetoothAdapter == null) 
    { 
     myLabel.setText("No bluetooth adapter available"); 
    } 

    if(!mBluetoothAdapter.isEnabled()) 
    { 
     Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBluetooth, 0); 
    } 

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
    if(pairedDevices.size() > 0) 
    { 
     for(BluetoothDevice device : pairedDevices) 
     { 
      if(device.getName().equals("MattsBlueTooth")) 
      { 
       mmDevice = device; 
       break; 
      } 
     } 
    } 
    myLabel.setText("Bluetooth Device Found"); 
} 

void openBT() throws IOException 
{ 
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID 
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);   
    mmSocket.connect(); 
    mmOutputStream = mmSocket.getOutputStream(); 
    mmInputStream = mmSocket.getInputStream(); 

    beginListenForData(); 

    myLabel.setText("Bluetooth Opened"); 
} 

void beginListenForData() 
{ 
    final Handler handler = new Handler(); 
    final byte delimiter = 10; //This is the ASCII code for a newline character 

    stopWorker = false; 
    readBufferPosition = 0; 
    readBuffer = new byte[1024]; 
    workerThread = new Thread(new Runnable() 
    { 
     public void run() 
     {     
      while(!Thread.currentThread().isInterrupted() && !stopWorker) 
      { 
       try 
       { 
        int bytesAvailable = mmInputStream.available();       
        if(bytesAvailable > 0) 
        { 
         byte[] packetBytes = new byte[bytesAvailable]; 
         mmInputStream.read(packetBytes); 
         for(int i=0;i<bytesAvailable;i++) 
         { 
          byte b = packetBytes[i]; 
          if(b == delimiter) 
          { 
    byte[] encodedBytes = new byte[readBufferPosition]; 
    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); 
    final String data = new String(encodedBytes, "US-ASCII"); 
    readBufferPosition = 0; 

           handler.post(new Runnable() 
           { 
            public void run() 
            { 
             myLabel.setText(data); 
            } 
           }); 
          } 
          else 
          { 
           readBuffer[readBufferPosition++] = b; 
          } 
         } 
        } 
       } 
       catch (IOException ex) 
       { 
        stopWorker = true; 
       } 
      } 
     } 
    }); 

    workerThread.start(); 
} 

void sendData() throws IOException 
{ 
    String msg = myTextbox.getText().toString(); 
    msg += "\n"; 
    mmOutputStream.write(msg.getBytes()); 
    myLabel.setText("Data Sent"); 
} 

void closeBT() throws IOException 
{ 
    stopWorker = true; 
    mmOutputStream.close(); 
    mmInputStream.close(); 
    mmSocket.close(); 
    myLabel.setText("Bluetooth Closed"); 
} 
} 

,這裏的佈局:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
tools:ignore="TextFields,HardcodedText" > 

<TextView 
    android:id="@+id/label" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Type here:" /> 

<EditText 
    android:id="@+id/entry" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/label" 
    android:background="@android:drawable/editbox_background" /> 

<Button 
    android:id="@+id/open" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_below="@id/entry" 
    android:layout_marginLeft="10dip" 
    android:text="Open" /> 

<Button 
    android:id="@+id/send" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignTop="@id/open" 
    android:layout_toLeftOf="@id/open" 
    android:text="Send" /> 

<Button 
    android:id="@+id/close" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignTop="@id/send" 
    android:layout_toLeftOf="@id/send" 
    android:text="Close" /> 

這裏是清單: 添加到應用

// permission must be enabled complete 
<manifest ....> 
    <application> 
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
     <uses-permission android:name="android.permission.BLUETOOTH" /> 

    </application> 
</manifest> 
+0

感謝您的東西代碼真的幫了我 – ppumkin

+3

我得到一個NullPointerException上線mmSocket = mmDevice.createRfcommSocketToServiceRecord(UUID);任何幫助,好嗎? –

+0

Tomas我想你可能有一個不正確的UUID爲設備?你使用什麼值? – bbill

5

我嘗試過從我的PC(MATLAB)傳輸連續數據(浮點值轉換爲字符串)到我的手機。但是,我的應用程序仍然誤讀了分隔符'\ n',仍然有數據出現亂碼。所以,我將字符'N'作爲分隔符而不是'\ n'(它可以是任何不會作爲數據一部分出現的字符),並且我的傳輸速度更快 - 延遲時間僅爲0.1秒在發送連續樣本之間 - 在接收器處具有超過99%的數據完整性,即在我發送的2000個樣本(浮點值)中,只有10個在我的應用中未被正確解碼。

我的答案總之是:選擇除'\ r'或'\ n'以外的分隔符,因爲與其他字符相比,這些字符會導致實時數據傳輸更多問題。如果我們的工作更多,可能是我們可以增加更多的傳輸速率。我希望我的回答可以幫助別人!

4

空連接的問題與findBT()函數有關。您必須將設備名稱從「MattsBlueTooth」更改爲設備名稱,並確認服務/設備的UUID。使用類似BLEScanner的應用程序在Android上進行驗證。

+0

如何確認任何設備/服務的UUID? –

0

看看令人難以置信的Bluetooth Serial類有onResume()能力,幫助我這麼多。 我希望這有助於;)

相關問題