【问题标题】:Android and Bluetooth hang (startActivityForResult)Android 和蓝牙挂起 (startActivityForResult)
【发布时间】:2013-02-05 01:45:19
【问题描述】:

我正在尝试改进一个实际代码,该代码可将蓝牙与 Android 手机连接到带有 Arduino(电子微控制器)的 Atmega。我可以接收数据并将数据发送到微控制器,但蓝牙需要在午餐我的应用程序之前打开,否则它将挂起并关闭。我确实检查了蓝牙适配器并请求用户更改蓝牙状态,如果它处于关闭状态,但似乎程序继续并尝试在获得用户选择的结果之前建立连接。我需要一些帮助来找到一个解决方案来阻止我的程序,直到用户输入他们的选择,或者甚至获得更好的解决方案。

我想说的是,我还是 Android 编程新手,我确实阅读了 Android 活动流程图。

我可以提供 logcat,但我检查了它,它清楚地表明我正在尝试使用蓝牙,即使它没有启用......

这是我的代码:

我要感谢任何可以为我指明正确方向的人

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

    setContentView(R.layout.activity_main);

    btnOn = (Button) findViewById(R.id.btnOn);                  // button LED ON
    btnOff = (Button) findViewById(R.id.btnOff);                // button LED OFF
    txtArduino = (TextView) findViewById(R.id.txtArduino);      // for display the received data from the Arduino

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState(); 

    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case RECIEVE_MESSAGE:                                                   // if receive massage
                byte[] readBuf = (byte[]) msg.obj;
                String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                sb.append(strIncom);                                                // append string
                int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                if (endOfLineIndex > 0) {                                           // if end-of-line,
                    sbprint = sb.substring(0, endOfLineIndex);              // extract string
                    sb.delete(0, sb.length());                                      // and clear
                    txtArduino.setText("Data from Arduino: " + sbprint); 
                    Log.e(TAG, "Arduino"+sbprint);

               //Test string value     
                    if(sbprint.matches("-?\\d+(\\.\\d+)?")) {
                        try{

                        Float sensorReading = Float.parseFloat(sbprint);
                        Log.e(TAG, "Sensor value"+sensorReading);
                        }catch(NumberFormatException e){
                            Log.e(TAG, "No int format sorry",e);

                        }
                    }   
                    if(sbprint.matches("test")){

                        Log.e(TAG, "garbage");
                    }

                   ///////

                    btnOff.setEnabled(true);
                    btnOn.setEnabled(true); 
                }
                //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                break;
            }
        };
    };





public void onResume() {
    super.onResume();

    Log.d(TAG, "...onResume - try connect...");

    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    /*try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }*/

    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    mBluetoothAdapter.cancelDiscovery();


    // Establish the connection.  This will block until it connects.
    Log.d(TAG, "...Connecting...");
    try {
      btSocket.connect();
      Log.d(TAG, "....Connection ok...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }

    // Create a data stream so we can talk to server.
    Log.d(TAG, "...Create Socket...");

    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();
}

【问题讨论】:

    标签: android bluetooth arduino


    【解决方案1】:

    您的所有代码都在 onResume 中。 onResume 将在活动启动时被调用,因此它几乎会立即执行。我没有看到任何应该延迟它的代码。如果您不想在用户选择某些东西之前尝试连接,那么所有连接代码都应该在按钮的单击处理程序或类似的东西中。

    【讨论】:

    • 也许我的问题表述不当,因为当用户选择具有 BluetoothAdapter.ACTION_REQUEST_ENABLE 意图的内容时,我确实想退出或连接。我不想要连接的特定按钮。我尝试使用 onActivityResult 但我可能没有正确使用它,因为它不起作用。
    【解决方案2】:

    除了@GabeSechan 关于您的所有代码都在onResume() 中的评论之外,您还在主活动线程中调用蓝牙connect(),根据this documentation 是一个阻塞调用并且“应该总是在与主活动线程分开的线程中执行”。

    【讨论】:

    • 关于线程的一个说明......如果我确实使用另一个线程,我会在 onResume() 中调用它吗?
    • 我也在学习这个。我们需要阅读developer.android.com/guide/components/… 以了解在后台线程中处理长时间运行和阻塞任务的最佳方法。
    猜你喜欢
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多