通过android中的RFCOMM接收字符串

时间:2014-03-27 19:29:19

标签: java android bluetooth

我试图通过Android中的RFCOMM收到一个字符串

我是android的新手,请帮助我 我可以发送数据 但接收失败

这是我的代码

请帮帮我

package com.example.btspp;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.UUID;
import java.util.regex.Pattern;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Buttons extends Activity {

private BluetoothAdapter btAdaptor;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");

Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

public String addressToConnect;
public static StringBuilder readStr;

TextView tv;
int aa;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_buttons);
    tv = (TextView) findViewById(R.id.textView1);
    addressToConnect = getIntent().getStringExtra("addressToConnect");

    connectToDevice(addressToConnect);

    Button btn = (Button) findViewById(R.id.button1);


    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            sendData("H");          

            // Toast.makeText(getBaseContext(), addressToConnect,
            // Toast.LENGTH_SHORT).show();
        }
    });



}





private void sendData(String message) {
    byte[] msgBuffer = message.getBytes();
    try {
        // final BT bt = new BT();
        outStream.write(msgBuffer);
        //readData();
    } catch (Exception e) {
        // TODO: handle exception

        Toast.makeText(getApplicationContext(),
                "Not Sent BT Data : " + e.getMessage(), Toast.LENGTH_SHORT)
                .show();
    }
}


/*private void readData(){
    String instring = "";
    try {
        inStream = btSocket.getInputStream();
    } catch (Exception e) {
        // TODO: handle exception
    }

    Scanner scan = new Scanner(new InputStreamReader(inStream));
    scan.useDelimiter(Pattern.compile("[\\r\\n]+"));
    instring = scan.next();
    scan = null;
    Toast.makeText(getApplicationContext(),
            "Got Data : " + instring, Toast.LENGTH_SHORT)
            .show();
    //return instring;

}*/
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 = inStream.available();                        
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        inStream.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()
                                    {
                                        tv.setText(data);
                                    }
                                });
                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                } 
                catch (IOException ex) 
                {
                    stopWorker = true;
                }
           }
        }
    });

    workerThread.start();
}

private void connectToDevice(String address) {
    btAdaptor = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice device = btAdaptor.getRemoteDevice(address);
    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        btSocket.connect();
        outStream = btSocket.getOutputStream();
        inStream = btSocket.getInputStream();
        beginListenForData();
        tv.setText("Bluetooth Opened");
        //listenForMessages(btSocket, readStr);
        // beginListenForData();

    } catch (IOException e) {
        // errorExit("Fatal Error",
        // "In onResume() and socket create failed: " + e.getMessage() +
        // ".");
        Toast.makeText(getApplicationContext(),
                "Not Connected : " + e.getMessage(), Toast.LENGTH_SHORT)
                .show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_buttons, menu);
    return true;
}

}

我是android的新手,请帮助我 我可以发送数据 但接收失败

这是我的代码

请帮帮我

1 个答案:

答案 0 :(得分:-1)

不是13“\ r”是通常的分隔符,而不是10?