Android和蓝牙挂起(startActivityForResult)

时间:2013-02-05 01:45:19

标签: android bluetooth arduino

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

我想说我还是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();
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

除了@ GabeSechan关于您onResume()中所有代码的评论之外,您还在主活动主题中调用蓝牙connect(),根据this documentation,它是阻止的调用和“应始终在与主活动线程分开的线程中执行”。