Android通过蓝牙发送命令失败

时间:2014-05-29 10:21:46

标签: android bluetooth command

我一直试图连接到MCU主板,不使用arduino代码,嵌入了蓝牙ICU芯片HC-06。我已成功地将我的Android设备与主板连接起来。在那之后,我尝试发送" 26 24 54 02 c9 00"作为纯字符串。但是,经过很长一段时间,设备没有响应。我甚至用AT命令检查发送了AT + NAMExyz和AT等。设备仍然没有响应。你能不能告诉我还有另一条出路吗?除了在Android设备上,我还需要做什么编程工作?如果我没有使用Arduino设备连接,我还需要观察和进行研究吗?以下是我的代码。

以下是我的logcat消息

07-29 16:45:50.701: D/dalvikvm(26944): Late-enabling CheckJNI
07-29 16:45:50.721: I/dalvikvm(26944): Enabling JNI app bug workarounds for target SDK version 7...
07-29 16:45:53.501: D/BluetoothCommandService(26944): start
07-29 16:45:53.501: D/BluetoothCommandService(26944): setState() 0 -> 1
07-29 16:45:55.361: D/dalvikvm(26944): GC_FOR_ALLOC freed 100K, 1% free 17103K/17236K, paused 14ms, total 14ms
07-29 16:46:04.211: D/BluetoothCommandService(26944): connect to: 00:14:01:22:18:12
07-29 16:46:04.211: D/BluetoothCommandService(26944): setState() 1 -> 2
07-29 16:46:04.211: I/BluetoothCommandService(26944): BEGIN mConnectThread
07-29 16:46:04.211: W/BluetoothAdapter(26944): getBluetoothService() called with no BluetoothManagerCallback
07-29 16:46:04.211: D/BluetoothSocket(26944): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[53]}
07-29 16:46:06.241: D/BluetoothCommandService(26944): connected
07-29 16:46:06.241: D/BluetoothCommandService(26944): create ConnectedThread
07-29 16:46:06.241: I/BluetoothCommandService(26944): BEGIN mConnectedThread
07-29 16:46:06.241: D/BluetoothCommandService(26944): setState() 2 -> 3
07-29 16:46:09.851: D/commmand(26944): &$R\x00\xc9
07-29 16:46:13.241: D/commmand(26944): &$R\x00\xc9
07-29 16:46:19.581: D/commmand(26944): &$V\x00\xcd
07-29 16:46:39.811: D/dalvikvm(26944): Debugger has detached; object registry had 1 entries
07-29 16:46:39.871: D/dalvikvm(26944): GC_CONCURRENT freed 48K, 1% free 17522K/17616K, paused 6ms+1ms, total 57ms
07-29 16:47:23.631: D/commmand(26944): &$R\x00\xc9
07-29 16:47:24.911: D/commmand(26944): &$R\x00\xc9
07-29 16:47:25.651: D/commmand(26944): &$R\x00\xc9
07-29 16:47:26.401: D/commmand(26944): &$V\x00\xcd
07-29 16:47:26.961: D/commmand(26944): &$R\x00\xc9
07-29 16:47:27.771: D/commmand(26944): &$R\x00\xc9
07-29 16:47:28.601: D/commmand(26944): &$R\x00\xc9
07-29 16:47:35.171: D/commmand(26944): &$R\x00\xc9
07-29 16:47:35.991: D/commmand(26944): &$R\x00\xc9
07-29 16:47:36.441: D/commmand(26944): &$R\x00\xc9
07-29 16:47:37.141: D/commmand(26944): &$V\x00\xcd
07-29 16:47:37.921: D/commmand(26944): &$V\x00\xcd
07-29 16:47:38.281: D/commmand(26944): &$V\x00\xcd
07-29 16:47:38.581: D/commmand(26944): &$V\x00\xcd
07-29 16:47:40.001: D/commmand(26944): &$R\x00\xc9




    package com.example.android.BluetoothChat;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.UUID;

    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.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.ToggleButton;

CUrrent:

以下是我的代码:

BluetoothCommandService.java

 public class BluetoothCommandService {
        private static final String TAG = "BluetoothCommandService";
        private static final boolean D = true;

        private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    // Member fields
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;
    //    private BluetoothDevice mSavedDevice;
    //    private int mConnectionLostCount;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    // Constants that indicate command to computer
    public static final int EXIT_CMD = -1;
    public static final int VOL_UP = 1;
    public static final int VOL_DOWN = 2;
    public static final int MOUSE_MOVE = 3;
    public static Context ctx ;
    /**
     * Constructor. Prepares a new BluetoothChat session.
     * @param context  The UI Activity Context
     * @param handler  A Handler to send messages back to the UI Activity
     */
    public BluetoothCommandService(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        //mConnectionLostCount = 0;
        ctx = context;
        mHandler = handler;
    }

    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(RemoteBluetooth.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start() {
        if (D) Log.d(TAG, "start");

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        setState(STATE_LISTEN);
    }
    public synchronized void connect(BluetoothDevice device) {
        if (D) Log.d(TAG, "connect to: " + device);

        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }

        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (D) Log.d(TAG, "connected");

        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();

        Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(RemoteBluetooth.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);


        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        ConnectedThread r;

        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }

        r.write(out);
    }

    public void write(int out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        setState(STATE_LISTEN);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(RemoteBluetooth.TOAST, "Unable to connect device");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {

        setState(STATE_LISTEN);
        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(RemoteBluetooth.TOAST, "Device connection was lost");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
       }
    }

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "create() failed", e);
            }
            mmSocket = tmp;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectThread");
            setName("ConnectThread");

            mAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {

                mmSocket.connect();
            } catch (IOException e) {
                e.printStackTrace();
                connectionFailed();
                // Close the socket
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() socket during connection failure", e2);
                }
                // Start the service over to restart listening mode
                BluetoothCommandService.this.start();
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (BluetoothCommandService.this) {
                mConnectThread = null;
            }

            // Start the connected thread
            connected(mmSocket, mmDevice);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

    public static String slurp(final InputStream is, final int bufferSize)
    {
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        try {
            final Reader in = new InputStreamReader(is, "UTF-8");
            try {
                for (;;) {
                    int rsz = in.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
            }
            finally {
                in.close();
            }
        }
        catch (UnsupportedEncodingException ex) {
            /* ... */
        }
        catch (IOException ex) {
            /* ... */
        }
        return out.toString();
    }
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];

            while (true) {
                try {
                    int bytes = mmInStream.read(buffer);
                    Log.d( "message" , slurp(mmInStream, 1024));
                    Toast.makeText(ctx, slurp(mmInStream, 1024), Toast.LENGTH_SHORT).show();
                    mHandler.obtainMessage(RemoteBluetooth.MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);

            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void write(int out) {
            try {
                mmOutStream.write(out);

            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                mmOutStream.write(EXIT_CMD);
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }
}

RemoteBluetooth.java

public class RemoteBluetooth extends Activity {

    private TextView mTitle;

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    private String mConnectedDeviceName = null;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothCommandService mCommandService = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        // If BT is not on, request that it be enabled.
        // setupCommand() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        // otherwise set up the command service
        else {
            if (mCommandService==null)
                setupCommand();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mCommandService != null) {
            if (mCommandService.getState() == BluetoothCommandService.STATE_NONE) {
                mCommandService.start();
            }
        }
    }

    private void setupCommand() {
        mCommandService = new BluetoothCommandService(this, mHandler);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mCommandService != null)
            mCommandService.stop();
    }

    private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
                BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case BluetoothCommandService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append("HC-06");
                    break;
                case BluetoothCommandService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothCommandService.STATE_LISTEN:
                case BluetoothCommandService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_DEVICE_NAME:
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                        + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                        Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                        .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
                // Attempt to connect to the device
                mCommandService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                setupCommand();
            } else {
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
        Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.discoverable:
        ensureDiscoverable();
            return true;
        }
        return false;
    }

    public static String hexadecimal(String input, String charsetName) 
            throws UnsupportedEncodingException {
        if (input == null) throw new NullPointerException();
        return asHex(input.getBytes(charsetName));
    }

    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();

    public static String asHex(byte[] buf)
    {
        char[] chars = new char[2 * buf.length];
        for (int i = 0; i < buf.length; ++i)
        {
            chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
            chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
        }
        return new String(chars);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {

            try{
                String syncCommand = "&$";
                String descriptor = "R";
                int datalength = 0;
                String data = "";
                if(datalength > 0 ){
                    String data1 = hexadecimal(String.valueOf(datalength)  , "UTF-8");
                    String data2 = hexadecimal(String.valueOf(data)  , "UTF-8");
                    data = data1 + data2;
                }else{
                    data =  "\\x00" ;
                }
                int checksum = 0x77; 
                String  descHex =   hexadecimal(String.valueOf(descriptor)  , "UTF-8");    
                checksum +=  ( Integer.parseInt(descHex,16)    );
                String checkSumString = "\\x" +  Integer.toHexString(checksum);                 
                String fullCommand = syncCommand +  descriptor + data + checkSumString;

                Log.d("commmand" , fullCommand);

                mCommandService.write(fullCommand.getBytes());

            }catch(Exception e){
                e.printStackTrace();
            }

        return true;
    }
    else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
        try{
            String syncCommand = "&$";
            String descriptor = "V";
            int datalength = 0;
            String data = "";
            if(datalength > 0 ){
                String data1 = hexadecimal(String.valueOf(datalength)  , "UTF-8");
                String data2 = hexadecimal(String.valueOf(data)  , "UTF-8");
                data = data1 + data2;
            }else{
                data =  "\\x00" ;
            }
            int checksum = 0x77; 
            String  descHex =   hexadecimal(String.valueOf(descriptor)  , "UTF-8");
        //  String  dataHex = datalength == 0 ? "\\x00" : hexadecimal(String.valueOf(datalength)  , "UTF-8");
        //  Log.d("descHex" , descHex);
        //  Log.d("dataHex" , dataHex);

            checksum +=  ( Integer.parseInt(descHex,16)  );

            String checkSumString = "\\x" +  Integer.toHexString(checksum);

            String fullCommand = syncCommand +  descriptor + data + checkSumString;
            Log.d("commmand" , fullCommand);
            mCommandService.write(fullCommand.getBytes());
        }catch(Exception e){
            e.printStackTrace();
        }
        return true;
    }

    return super.onKeyDown(keyCode, event);
}
}

原文:

public class BluetoothChat extends Activity implements OnClickListener {

        Button Connect;
        ToggleButton OnOff;
        TextView Result;
        private String dataToSend;

        private static final String TAG = "Jon";
        private BluetoothAdapter mBluetoothAdapter = null;
        private BluetoothSocket btSocket = null;
        private OutputStream outStream = null;
        private static String address = "00:1a:a1:22:11:12";
        private static final UUID MY_UUID = UUID
                .fromString("00001101-0000-1000-8000-00805F9B34FB");
        private InputStream inStream = null;
        Handler handler = new Handler(); 
        byte delimiter = 100;
        boolean stopWorker = false;
        int readBufferPosition = 0;
        byte[] readBuffer = new byte[1024];

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Connect = (Button) findViewById(R.id.conne

ct);
        OnOff = (ToggleButton) findViewById(R.id.tgOnOff);
        Result = (TextView) findViewById(R.id.msgJonduino);

        Connect.setOnClickListener(this);
        OnOff.setOnClickListener(this);

        CheckBt();
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        Log.e("Jon", device.toString());

    }

    @Override
    public void onClick(View control) {
        switch (control.getId()) {
        case R.id.connect:
            Connect();
            break;
        case R.id.tgOnOff:
            if (OnOff.isChecked()) {
                dataToSend = "26 24 54 02 c9 00";
                Log.e("JonS", dataToSend);
                writeData(dataToSend);
            } else if (!OnOff.isChecked()) {
                dataToSend = "26245200c900";
                Log.e("JonS", dataToSend);
                writeData(dataToSend);
            }
            break;
        }
    }

    private void resetConnection() {
    //  setState(STATE_NONE);
        Log.d(TAG, "reset connection");
        if (inStream != null) {
            try {
                inStream.close();
            } catch (Exception e) {
                Log.d(TAG,"exception in closing inputstream - " + e.getMessage());
            }
            inStream = null;
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (Exception e) {
                Log.d(TAG,"exception in closing outputstream - " + e.getMessage());
            }
            outStream = null;
        }
        if (btSocket != null) {
            try {
                btSocket.close();
            } catch (Exception e) {
                Log.d(TAG,"exception in closing socket - " + e.getMessage());
            }
            btSocket = null;
        }
        Connect();
    }

    private void CheckBt() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
                    Toast.LENGTH_SHORT).show();
        }

        if (mBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(),
                    "Bluetooth null !", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    public void Connect() {
        Log.d(TAG, address);
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        Log.d(TAG, "Connecting to ... " + device);
        mBluetoothAdapter.cancelDiscovery();
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            btSocket.connect();
            Log.d(TAG, "Connection made.");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                Log.d(TAG, "Unable to end the connection");
            }
            Log.d(TAG, "Socket creation failed");
        }

        beginListenForData();
    }

    private void writeData(String data) {
        try {
            outStream = btSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Bug BEFORE Sending stuff", e);
        }

        String message = data;
        byte[] msgBuffer = message.getBytes();

        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Bug while sending stuff", e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            if(btSocket!=null){
                btSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void beginListenForData()   {
        try {
            inStream = btSocket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Thread 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);
                                    //US-ASCII
                                    final String data = new String(encodedBytes, "UTF-8");
                                    readBufferPosition = 0;
                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {

                                            if(Result.getText().toString().equals("..")) {
                                                Result.setText(data);
                                            } else {
                                                Result.append("\n"+data);
                                            }

                                            /* You also can use Result.setText(data); it won't display multilines
                                             */

                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        ex.printStackTrace();
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }
}

1 个答案:

答案 0 :(得分:1)

从日志中看,配对和连接建立到远程设备是成功的。要进一步调试应用程序未接收数据的原因,您需要查找远程设备的响应是否在蓝牙堆栈接收,然后将其发送到应用程序。为此,您需要捕获窥探日志。在JB和更高版本中,在设置中启用后,它将在/sdcard/btsnoop_hci.log下找到。