2012-06-11 4 views
1

내 프로그램이 서버로 작동하는 내장 된 블루투스 장치에 연결됩니다. 근처의 블루투스 장치를 성공적으로 찾았지만 새 장치에 연결하려고하면 BluetoothSocket.connect()를 호출 할 때 IO 예외로 인해 프로그램이 중단됩니다. 나는 누군가가 저를 도울 수 있다면 정말 감사 할 것입니다 그래서 무슨 일이 일어나고 있는지 알아내는 데 문제가 있습니다.BluetoothSocket.connect() throw IOException

무작위로 생성하는 UUID와 관련이 있을지 모르지만 완전히 확신 할 수는 없습니다.

감사합니다.

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    btnScanDevice = (Button) findViewById(R.id.scandevice); 

    stateBluetooth = (TextView) findViewById(R.id.bluetoothstate); 
    startBluetooth(); 

    listDevicesFound = (ListView) findViewById(R.id.devicesfound); 
    btArrayAdapter = new ArrayAdapter<String>(AndroidBluetooth.this, 
      android.R.layout.simple_list_item_1); 
    listDevicesFound.setAdapter(btArrayAdapter); 

    CheckBlueToothState(); 

    btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener); 

    registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); 

    listDevicesFound.setOnItemClickListener(new OnItemClickListener() 
    { 
     public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
     { 
      myBtDevice = btDevicesFound.get(arg2); 
      try { 
       btSocket = myBtDevice.createRfcommSocketToServiceRecord(MY_UUID); 
       iStream = btSocket.getInputStream(); 
       oStream = btSocket.getOutputStream(); 
      } catch (IOException e) { 
       Log.e("Bluetooth Socket", "Bluetooth not available, or insufficient permissions"); 
      } catch (NullPointerException e) { 
       Log.e("Bluetooth Socket", "Null Pointer One"); 
      } 
      myBtAdapter.cancelDiscovery(); 
      CheckBlueToothState(); 
      try { 
       btSocket.connect(); 
      } catch (IOException e) { 
       Log.e("Bluetooth Socket", "IO Exception"); 
      } catch (NullPointerException e) { 
       Log.e("Bluetooth Socket", "Null Pointer Two"); 
      } 
     } 

    }); 
} 

private void CheckBlueToothState() { 
    if(myBtAdapter == null) { 
     stateBluetooth.setText("Bluetooth NOT supported"); 
    } else { 
     if(myBtAdapter.isEnabled()) { 
      if(myBtAdapter.isDiscovering()) { 
       stateBluetooth.setText("Bluetooth is currently " + 
         "in device discovery process."); 
      } else { 
       stateBluetooth.setText("Bluetooth is Enabled."); 
       btnScanDevice.setEnabled(true); 
      } 
     } else { 
      stateBluetooth.setText("Bluetooth is NOT enabled"); 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
     } 
    } 
} 

private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener() { 
    public void onClick(View arg0) { 
     btArrayAdapter.clear(); 
     myBtAdapter.startDiscovery(); 
    } 
}; 


@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if(requestCode == REQUEST_ENABLE_BT) { 
     CheckBlueToothState(); 
    } 
} 

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if(BluetoothDevice.ACTION_FOUND.equals(action)) { 
      BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      btDevicesFound.add(btDevice); 
      btArrayAdapter.add(btDevice.getName() + "\n" + btDevice.getAddress()); 
      btArrayAdapter.notifyDataSetChanged(); 
     }   
    } 
}; 
public static void startBluetooth(){ 
    try { 
     myBtAdapter = BluetoothAdapter.getDefaultAdapter(); 
     myBtAdapter.enable(); 
    } catch (NullPointerException ex) { 
     Log.e("Bluetooth", "Device not available"); 
    } 
} 

public static void stopBluetooth() { 
    myBtAdapter.disable(); 
} 

답변

3

게시 한 코드에는 두 가지 문제가 있지만 충돌과 관련된 것은 하나뿐입니다.

대개 logcat의 충돌로 인해 "명령이 거부되었습니다"와 같은 메시지가 표시됩니다. UUID는 임베디드 장치에서 게시 된 서비스를 가리켜 야하는 값이며 은 임의로 생성 할 수 없습니다. 즉, 액세스하려는 RFCOMM SPP 연결에는 해당 서비스를 식별하기 위해 게시하는 특정 UUID가 있으며, 소켓을 만들 때 일치하는 UUID를 사용해야합니다.

This blog post I wrote은 프로그램에 삽입해야하는 적절한 UUID를 얻기 위해 기기를 쿼리하는 방법을 도와 줄 수 있습니다. 안드로이드 4.0 이전에 SDK는 당신이 그것을 (블루투스 OEM 등에서 얻은) 미리 알았다고 아주 가깝게 생각했습니다. 그래서 당신의 장치에서 그것을 발견했습니다. 운좋게 4.0.3 장치를 가지고 있다면 fetchUuidsWithSdp()getUuids()이 이제는 공개 메서드가되어 게시 된 모든 서비스와 관련 UUID 값을 직접 호출 할 수 있습니다.

아마 나중에 당신을 공격하면 연결 한 후 때까지 아마이 같이 당신의 방법을 다시 작성해야합니다, 그래서 당신이 당신의 소켓에서 데이터 스트림을 얻을 수 있다는 것입니다 코드와 두 번째 문제 :

 myBtDevice = btDevicesFound.get(arg2); 
     try { 
      btSocket = myBtDevice.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { 
      Log.e("Bluetooth Socket", "Bluetooth not available, or insufficient permissions"); 
     } 

     myBtAdapter.cancelDiscovery(); 
     CheckBlueToothState(); 
     try { 
      btSocket.connect(); 
      //Get streams after connect() returns without error 
      iStream = btSocket.getInputStream(); 
      oStream = btSocket.getOutputStream(); 
     } catch (IOException e) { 
      Log.e("Bluetooth Socket", "IO Exception"); 
     } catch (NullPointerException e) { 
      Log.e("Bluetooth Socket", "Null Pointer Two"); 
     } 

HTH

+0

대단히 감사합니다. 불행히도, 나는이 응용 프로그램에 대한 안드로이드 2.0과 함께 일하고 있습니다. 원래는 특정 UUID 일 것이라고 생각했지만 어디서나 찾을 수 없었습니다. 당신이 어디를 보는지, 어떻게 보는지 알면, 나는 그것을 많이 고맙게 여길 것입니다. 응용 프로그램은 Lenovo Ideapad A1에서 실행되며 내장형 RN-41 블루투스 칩에 연결하려고 시도하고 있습니다. 또한 하나의 칩에만 연결되는 것이 아니라 여러 개의 다른 칩에 연결할 수 있어야합니다 (동시에는 아니지만 하나에서 연결을 끊고 다른 칩을 찾을 수 있음). 다시 감사합니다 – JuiCe

+1

그래서 ... 블로그 게시물을 읽고 그것은 2.0에서 할 방법을 알려줍니다 – Devunwired

+0

하하 미안 해요 링크를 클릭하기 전에 게시했지만, 나는 그것을 읽었습니다. 도움을 많이 주셔서 고마워요. – JuiCe