1

我正在尝试改进一个实际代码,该代码将蓝牙与 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();
}
4

2 回答 2

1

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

于 2013-02-05T02:02:23.317 回答
0

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

于 2013-02-05T02:15:24.930 回答