1

AndroidフォンとArduino(電子マイクロコントローラー)を使用してAtmegaにBluetooth接続する実際のコードを改善しようとしています。マイクロコントローラーとの間でデータを送受信できますが、アプリケーションを起動する前に Bluetooth を ON にする必要があります。そうしないと、ハングして閉じてしまいます。Bluetooth アダプターを確認し、Bluetooth の状態が OFF の場合は変更するようにユーザーに要求しますが、プログラムは続行され、ユーザーの選択の結果を取得する前に接続を試みているようです。ユーザーが選択を入力するまでプログラムをブロックするか、より良い解決策を得るまで、解決策を見つける手助けが必要です。

私はまだ Android プログラミングの初心者であり、Android アクティビティ フローチャートを読みました。

logcat を提供できますが、調べたところ、Bluetooth が有効になっていない場合でも使用しようとしていることが明確に示されています ...

これが私のコードです:

私を正しい方向に向けてくれる人に感謝したい

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

In addition to @GabeSechan's comment about all of your code being in onResume(), you are also calling the Bluetooth connect() in your main activity thread which according to the this documentation is a blocking call and "should always be performed in a thread separate from the main activity thread".

于 2013-02-05T02:15:24.930 に答える