【问题标题】:Send Command to Bluetooth from Android device从 Android 设备向蓝牙发送命令
【发布时间】:2016-12-15 08:35:57
【问题描述】:

我在将命令从我的 android 设备发送到蓝牙设备时遇到问题。

蓝牙与微控制器相关联。我的努力如下:

    public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_ENABLE_BT = 2;
    private BluetoothAdapter mBluetoothAdapter;

    public static final String TAG = "CustomPOC BLEEEEEEE";
    private Button btn_send;
    private BluetoothDevice mdevice;
    private Handler mHandler;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        btn_send = (Button)findViewById(R.id.senddata);

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Log.i(TAG, "onClick - BT not enabled yet");
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        pairedOrNot();


        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectThread = new ConnectThread(mdevice);
                mConnectThread.start();
               // new ConnectAsynk(mdevice).execute();
            }
        });
    }

    private void pairedOrNot() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        List<String> s = new ArrayList<String>();
        for(BluetoothDevice bt : pairedDevices) {
            s.add(bt.getAddress());
            s.add(bt.getName());
            if("08:7C:BE:00:00:01".equals(bt.getAddress())) {
                mdevice = bt;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();

                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                Log.e(TAG, "wrong request code");
                break;
        }
    }

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            mmDevice = device;
            try {

                tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

                /*Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                tmp = (BluetoothSocket) m.invoke(device, 1);*/
                System.out.println("BTTTTTTTTTTT  Address   "+mmDevice.getAddress());
                BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mmDevice.getAddress());
//                Method m;
//                m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
//                tmp = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1));
            }
            catch (Exception e){
             e.printStackTrace();
            }
            mmSocket = tmp;
        }
        public void run() {
            mBluetoothAdapter.cancelDiscovery();

            try {
                mmSocket.connect();

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

                // Cancel the thread that completed the connection
                if (mConnectThread != null) {
                    mConnectThread.cancel();
                    mConnectThread = null;
                }

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

                 ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
                 mConnectedThread.start();
            } catch (IOException connectException) {
                try {
                    connectException.printStackTrace();
                    mmSocket.close();
                } catch (IOException closeException) { }

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

        }
        public void cancel(){
            try {
                mmSocket.close();
            } catch (IOException e) { e.printStackTrace();}
        }

    }


    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        public ConnectedThread(BluetoothSocket socket) {
            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];
            int begin = 0;
            int bytes = 0;
            while (true) {
                try {
                    bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
                    for(int i = begin; i < bytes; i++) {
                        if(buffer[i] == "1010101100000001000000100000000100001110".getBytes()[0]) {
                            mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
                            begin = i + 1;
                            if(i == bytes - 1) {
                                bytes = 0;
                                begin = 0;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

当我通过

检查连接状态时,很少有提示
tmp.isConnected()

我发现它正在返回一个

假的

价值。

我想将此命令(1010101100000001000000010000000100001110)发送到外部蓝牙。但我遇到了问题。应用程序启动时的日志跟踪如下:

08-17 07:48:39.718: W/art(14551): Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.
drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, 
android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable

当点击按钮 btn_send 时,我在日志跟踪中收到以下消息:

08-17 07:51:32.046: W/BluetoothAdapter(14984): getBluetoothService() called with no BluetoothManagerCallback
08-17 07:51:38.448: W/System.err(14984): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
08-17 07:51:38.449: W/System.err(14984):    at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:573)
08-17 07:51:38.449: W/System.err(14984):    at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:584)
08-17 07:51:38.449: W/System.err(14984):    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:321)
08-17 07:51:38.449: W/System.err(14984):    at com.mahmad.custompoc11aug.MainActivity$ConnectThread.run(MainActivity.java:164)

调试后我发现问题出在这一行

mmSocket.connect();

清单文件中提供了所有必需的权限。请帮我解决这个问题。提前致谢。

【问题讨论】:

  • 您附加的 logcat 输出是无关紧要的,因为在您的代码中,所有异常都被“沉默”了——您捕获它们并且什么都不做。捕获异常时您必须做的最低限度是记录它(例如e.printStackTrace())。请重新运行您的代码并记录所有异常,然后我们可能会为您提供帮助
  • 问题已更新。请检查一下。
  • 再一次 - 你怎么知道一路上没有抛出异常?抛出异常是为了通知您出现问题,但您只是忽略它们。将e.printStackTrace() 添加到所有catch 子句并发布整个logcat 输出。
  • 感谢您的回复,但上面发布的日志跟踪仅显示在 Studio 跟踪中。但调试后我在“mmSocket.connect();”行中发现了问题。请帮助我,否则任何建议都会很重要。
  • 请注意 - 我正在使用“RS232 传输协议:1200, N, 8, 1”。

标签: android bluetooth


【解决方案1】:

我试过这个库。你也可以试试 https://github.com/palaima/AndroidSmoothBluetooth

【讨论】:

  • 以上库有“构建问题”。感谢帮助。我正在尝试构建它。当我有机会时,我会回复你。
【解决方案2】:

我有一个非常相似的代码并且它正在工作,这可能是我正在重置线程的主要区别之一:

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

// Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

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

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

就在你这样做之后:

mmSocket.connect();

希望对你有帮助。

【讨论】:

  • 感谢您的帮助,但它对我不起作用。任何进一步的建议都会非常有帮助。调试后在“mmSocket.connect();”这一行有问题
【解决方案3】:

正如您所提到的,问题存在于mmSocket.connect(); 行,因此问题不在于您发送命令时,而是在创建连接时,即您无法在打开或连接状态下检索BluetoothSocket

你应该怎么做?

尝试将以下代码与 UUID 一起使用,它对我的​​蓝牙适配器有效。

UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); createInsecureRfcommSocketToServiceRecord(MY_UUID)

让我知道这是否适合您。

还要检查, https://stackoverflow.com/a/18786701/1503130

【讨论】:

  • 嗨.. Prateek,你能发送命令吗?需要您的意见
猜你喜欢
  • 2015-06-26
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 2013-01-16
  • 2012-02-29
  • 1970-01-01
相关资源
最近更新 更多