2013-07-20 3 views
11

나는이 문제를 오래 동안 가지고 있었고 알아낼 수 없었습니다.android 블루투스를 연결할 수 없습니다.

나는 모든 쌍으로 된 장치를 목록보기에 넣는 안드로이드 응용 프로그램을 가지고 있습니다. 목록 항목 중 하나를 클릭하면 해당 블루투스 장치에 연결하기위한 요청이 시작됩니다.

해당 주소가있는 장치 목록을 얻을 수 있습니다. 문제는 일단 연결하려고하면 socket.connect()에서 IOException이 발생합니다. 다음과 같이

오류 메시지는 다음과 같습니다 은 "읽기에 실패 연결 소켓 RET를 읽을 폐쇄 또는 제한 될 수 있습니다 -1"

가 여기 내 코드입니다. ANY 제안을 부탁드립니다. 나는 이것에 상당히 집착하고있다.

fyi : "onEvent"메서드는 콜백을 단순화하는 라이브러리이므로 해당 부분이 작동합니다. 사용자가 클릭이 목록 항목에이 방법이라고 "공공 무효의 onEvent (EventMessage.DeviceSelected 이벤트)는"

public class EcoDashActivity extends BaseActivity { 

public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 


private BluetoothAdapter mBluetoothAdapter; 
private int REQUEST_ENABLE_BT = 100; 
private ArrayList<BluetoothDevice> mDevicesList; 
private BluetoothDeviceDialog mDialog; 
private ProgressDialog progressBar; 
private int progressBarStatus = 0; 
private Handler progressBarHandler = new Handler(); 


@Override 
public void onCreate(final Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.main); 

    mDevicesList = new ArrayList<BluetoothDevice>(); 

    // Register the BroadcastReceiver 
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); 

    setupBluetooth(); 
} 

private void setupBluetooth() { 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if (mBluetoothAdapter == null) { 
     // Device does not support Bluetooth 
     Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show(); 
    } 

    if (!mBluetoothAdapter.isEnabled()) { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
    } else { 
     searchForPairedDevices(); 
     mDialog = new BluetoothDeviceDialog(this, mDevicesList); 
     mDialog.show(getFragmentManager(), ""); 
    } 

} 

private void searchForPairedDevices() { 

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
    // If there are paired devices 
    if (pairedDevices.size() > 0) { 
     // Loop through paired devices 
     for (BluetoothDevice device : pairedDevices) { 
      // Add the name and address to an array adapter to show in a ListView 
      mDevices.add(device.getName() + "\n" + device.getAddress()); 
      mDevicesList.add(device); 
     } 
    } 
} 


private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     // When discovery finds a device 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Get the BluetoothDevice object from the Intent 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      // Add the name and address to an array adapter to show in a ListView 
      mDevicesList.add(device); 
     } 
    } 
}; 


@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    unregisterReceiver(mReceiver); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (requestCode == REQUEST_ENABLE_BT) { 
     if (resultCode == RESULT_OK) { 
      Toast.makeText(this, "BT turned on!", Toast.LENGTH_SHORT).show(); 
      searchForPairedDevices(); 

      mDialog = new BluetoothDeviceDialog(this, mDevicesList); 
      mDialog.show(getFragmentManager(), ""); 
     } 
    } 

    super.onActivityResult(requestCode, resultCode, data); 
} 


public void onEvent(EventMessage.DeviceSelected event) { 

    mDialog.dismiss(); 

    BluetoothDevice device = event.getDevice(); 

    ConnectThread connectThread = new ConnectThread(device); 
    connectThread.start(); 
} 


public class ConnectThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 

    public ConnectThread(BluetoothDevice device) { 
     // Use a temporary object that is later assigned to mmSocket, 
     // because mmSocket is final 
     BluetoothSocket tmp = null; 
     mmDevice = device; 

     // Get a BluetoothSocket to connect with the given BluetoothDevice 
     try { 
      // MY_UUID is the app's UUID string, also used by the server code 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { } 
     mmSocket = tmp; 
    } 

    public void run() { 
     setName("ConnectThread"); 
     // Cancel discovery because it will slow down the connection 
     mBluetoothAdapter.cancelDiscovery(); 

     try { 
      // Connect the device through the socket. This will block 
      // until it succeeds or throws an exception 
      Log.d("kent", "trying to connect to device"); 
      mmSocket.connect(); 
      Log.d("kent", "Connected!"); 
     } catch (IOException connectException) { 
      // Unable to connect; close the socket and get out 
      try { 
       Log.d("kent", "failed to connect"); 

       mmSocket.close(); 
      } catch (IOException closeException) { } 
      return; 
     } 

     Log.d("kent", "Connected!"); 
    } 

    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

여기 내 로그 캣입니다. 꽤 짧다.

07-22 10:37:05.129: DEBUG/kent(17512): trying to connect to device 
07-22 10:37:05.129: WARN/BluetoothAdapter(17512): getBluetoothService() called with no BluetoothManagerCallback 
07-22 10:37:05.129: DEBUG/BluetoothSocket(17512): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[98]} 
07-22 10:37:40.757: DEBUG/dalvikvm(17512): GC_CONCURRENT freed 6157K, 9% free 62793K/68972K, paused 7ms+7ms, total 72ms 
07-22 10:38:06.975: DEBUG/kent(17512): failed to connect 
07-22 10:38:06.975: DEBUG/kent(17512): read failed, socket might closed or timeout, read ret: -1 

마지막 줄이 시도/캐치의 "캐치"섹션에 있음 ... 난 그냥 오류 메시지를 기록하고 있습니다.

"장치에 연결하려고"및 젤리 빈 블루투스 스택은 다른 버전에서 현저하게 다른

+0

어떤 Android 버전입니까? 완전히 다른 블루투스 스택을 가지고있는 젤리 빈과 스택 문제 일 수 있습니다. 페어링을 먼저 시도한 다음 다시 시도하십시오. – Slartibartfast

+0

또한 logcat 게시하십시오. – Slartibartfast

+0

@Slartibartfast 현재 4.2.2 Nexus 4에서 작업 중입니다. logcat으로 질문을 업데이트 할 것입니다. –

답변

14

"연결 실패"사이에 약 20 제 2 간극이있다, 유의하시기 바랍니다.

이 도움이 될 : 요점에서 http://wiresareobsolete.com/wordpress/2010/11/android-bluetooth-rfcomm/

: UUID가 임베디드 장치에 게시 된 서비스를 지정해야합니다 값, 그것은 단지 무작위로 생성되지 않습니다. 액세스하려는 RFCOMM SPP 연결에는 해당 서비스를 식별하기 위해 게시하는 특정 UUID가 있으며 소켓을 만들면 동일한 UUID와 일치해야합니다.

4.0.3 장치 이상을 대상으로하는 경우 fetchUuidsWithSdp()getUuids()을 사용하여 게시 된 모든 서비스와 관련 UUID 값을 찾습니다. 이전 버전과의 호환성을 위해

+0

GetUUIDs()는 ID 목록을 반환합니다. 어떤 것을 사용해야하는지 어떻게 알 수 있습니까? –

+0

방금 ​​반환 한 모든 UUID를 시도했는데 동일한 문제가있었습니다. –

+0

그냥 테스트를 위해 새 앱에 복사/붙여 넣을 수있는 완전한 코드 예제를 알고 있습니까? –

0

소켓을 연결 한 후 동일한 오류 메시지가 나타납니다. 소켓이 이미 연결되어 있는지 단순히 확인했습니다.

if(!mmSocket.isConnected()) 
      mmSocket.connect(); 

Android 4.4.2 (Moto G)에서 테스트를 진행했습니다.

관련 문제