2013-02-05 2 views
1

나는 Arduino (전자 마이크로 컨트롤러)와 함께 Atmega에 안드로이드 전화와 블루투스 연결을 개선하기 위해 노력하고있어. 마이크로 컨트롤러로 데이터를 보내고받을 수는 있지만 블루투스를 켜기 전에 애플리케이션을 점심 식사에 올려야합니다. 그렇지 않으면 멈추거나 닫힙니다. 나는 블루투스 어댑터를 확인하고 사용자가 블루투스 상태를 변경하도록 요청한다. OFF 상태이지만 프로그램을 계속 진행하고 사용자 선택 결과를 얻기 전에 연결을 시도하는 것 같다. 사용자가 자신의 선택을 입력하거나 더 나은 솔루션을 얻을 때까지 프로그램을 차단하는 해결책을 찾기 위해 도움을 받고 싶습니다.안드로이드와 블루투스 응답 (startActivityForResult)

나는 여전히 Android 프로그래밍에 익숙하지 않으며 Android 활동 흐름도를 읽었습니다. 내가 감사 누구 원하는

:

여기

내 코드는 ... 내가 로그 캣을 제공 할 수 있습니다,하지만 난 그것을 검사하고 명확 내가이 활성화 아니더라도 블루투스를 사용하는 것을 시도하고 있음을 명시 올바른 방향으로 나를 가리킬 수 있습니다.

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(); 
} 

답변

1

모든 코드는 onResume에 있습니다. onResume은 액티비티가 시작될 때 바로 호출되기 때문에 거의 즉시 실행됩니다. 거기에 전혀 지연되지 않아야하는 코드가 없습니다. 사용자가 무언가를 선택할 때까지 연결을 시도하지 않으려는 경우 모든 연결 코드는 버튼의 클릭 핸들러 또는 유사해야합니다. onResume()에있는 모든 코드에 대한 @ GabeSechan의 의견뿐만 아니라

+0

사용자가 BluetoothAdapter.ACTION_REQUEST_ENABLE 인 텐트를 사용하여 무언가를 선택하면 종료하거나 연결하기를 원하기 때문에 제 질문이 잘못 작성되었을 수 있습니다. 나는 연결을위한 특정 버튼을 원하지 않는다. 나는 onActivityResult를 사용하려고 시도했지만 작동하지 않기 때문에 올바르게 사용하지 않을 것입니다. – Mathieu660

0

, 당신은 또한 항상 별도의 스레드에서 수행되어야한다 "는 this documentation에 따라하는 당신의 주요 활동 스레드에서 차단 호출을 블루투스 connect()입니다 호출하고 있습니다 주요 활동 스레드에서 ".

+0

스레드에 대한 설명 하나만 ... 다른 스레드를 사용하면 onResume()에서 호출합니까? – Mathieu660

+0

나는 이것을 배우고있다. 백그라운드 스레드에서 장기 실행 및 차단 태스크를 처리하는 가장 좋은 방법을 배우려면 http://developer.android.com/guide/components/processes-and-threads.html을 읽어야합니다. – HeatfanJohn