2014-11-27 3 views
0

블루투스를 통해 스마트 폰을 평가 보드와 페어링 할 앱을 개발 중입니다. 나는 보드를 휴대폰에서 찾았고 그것들을 쌍으로 만들었지 만, 이런 일이 생기면 연결 부위가 없어졌습니다. 나는 다른 애플 리케이션과 그들을 짝 지우려고 노력하고 잘 작동하므로 내 코드에 뭔가 있어야합니다. 이들은 내 애플 리케이션이 연결을 만들기 위해 따라야 할 단계들입니다.블루투스 연결이 끊어졌습니다

MainActivity :

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    /*Gets bluetooth adapter*/ 
    GlobalVar.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    /*Resgisters receiver*/ 
    registerReceiver(bluetoothDeviceSelectedReceiver, new IntentFilter(
      "android.bluetooth.devicepicker.action.DEVICE_SELECTED")); 
    /*Calls method to make conection and pair devices*/ 
    newConection(); 
} 

public void newConection() { 
    /*Our device does not support BT*/ 
    if (GlobalVar.mBluetoothAdapter == null) { 
     Toast.makeText(this, R.string.bluetooth_not_available, Toast.LENGTH_LONG).show(); 
     finish(); 
     return; 
    } 
    /*Enables BT if is disabled*/ 
    if (!GlobalVar.mBluetoothAdapter.isEnabled()) { 
     Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT); 
     return; 
    } 
    /*If is already enabled, starts session*/ 
    else { 
     GlobalVar.mConnections = new ManageConnection(MainActivity.this, this); 
    } 
    /*Opens activity to select device*/ 
    openSelectDevice(); 
} 


/**Starts activity to select device*/ 
public void openSelectDevice() { 
    startActivity(new Intent("android.bluetooth.devicepicker.action.LAUNCH") 
    .putExtra("android.bluetooth.devicepicker.extra.NEED_AUTH", false) 
    .putExtra("android.bluetooth.devicepicker.extra.FILTER_TYPE", 0) 
    .setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)); 
} 


@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case REQUEST_ENABLE_BT: 
      if (resultCode == RESULT_OK) { 
       /*Starts session*/ 
       GlobalVar.mConnections = new ManageConnection(this, this); 
       openSelectDevice(); 
      } 
      break; 
    } 
} 


/**Receiver to make somethign when a device is selected to pair*/ 
public BroadcastReceiver bluetoothDeviceSelectedReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     /*Gets device*/ 
     BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
     GlobalVar.mConnections.cancelClient(); 
     GlobalVar.mConnections.startClient(device, MainActivity.this); 
    } 
}; 

ManageConnections :

/**Constructor*/ 
public ManageConnection(Context context, ConnectionListener connectionListener) { 
    this.connectionListener = connectionListener; 
} 

public synchronized void startClient(BluetoothDevice device, ConnectionListener cnListener) { 
    /*Cancel any thread attempting to make a connection*/ 
    if (mState == STATE_CONNECTING) { 
     if (GlobalVar.clientConnectionThread != null) { 
      GlobalVar.clientConnectionThread.cancel(); 
      GlobalVar.clientConnectionThread = null; 
     } 
    } 
    /*Cancel any thread currently running a connection*/ 
    if (GlobalVar.connectedThread != null) { 
     GlobalVar.connectedThread.cancel(); 
     GlobalVar.connectedThread = null; 
    } 
    /*Start the thread to connect with the given device*/ 
    GlobalVar.clientConnectionThread = new ClientConnectionThread(device, cnListener); 
    GlobalVar.clientConnectionThread.start(); 
} 

ClientConectionThread :

public ClientConnectionThread(BluetoothDevice device, ConnectionListener connectionListener) { 
    this.connectionListener = connectionListener; 
    BluetoothSocket socketTemp = null; 

    try { 
     socketTemp = device.createRfcommSocketToServiceRecord(GlobalVar.MY_UUID); 
    } catch (IOException e) { 
    } 
    socket = socketTemp; 
} 

@Override 
public void run() { 
    try { 
     socket.connect(); 
     connectionListener.onConnected(socket); 
    } catch (IOException e) { 
     try { 
      socket.close(); 
     } catch (IOException e1) {} 
    } 
} 

MannageConections :

public synchronized void startConnected(BluetoothSocket socket, Activity activity, ConnectionListener cnListener) { 
    /*Cancel the thread that completed the connection*/ 
    if (GlobalVar.clientConnectionThread != null) { 
     GlobalVar.clientConnectionThread.cancel(); 
     GlobalVar.clientConnectionThread = null; 
    } 
    /*Cancel any thread currently running a connection*/ 
    if (GlobalVar.connectedThread != null) { 
     GlobalVar.connectedThread.cancel(); 
     GlobalVar.connectedThread = null; 
    } 
    /*Cancel the accept thread because we only want to connect to one device*/ 
    if (GlobalVar.serverConnectionThread != null) { 
     GlobalVar.serverConnectionThread.cancel(); 
     GlobalVar.serverConnectionThread = null; 
    } 
    /*Start the thread to manage the connection and perform transmissions*/ 
    GlobalVar.connectedThread = new ConnectedThread(socket, activity, cnListener); 
    GlobalVar.connectedThread.start(); 
} 

ConnectedThread가 :

public ConnectedThread(BluetoothSocket socket, Activity activity, ConnectionListener connectionListener) { 
    this.socket = socket; 
    this.activity = activity; 
    this.connectionListener = connectionListener; 

    InputStream inTemp = null; 
    OutputStream outTemp = null; 

    try { 
     inTemp = socket.getInputStream(); 
     outTemp = socket.getOutputStream(); 
    } catch (IOException e) { 
    } 
    inputStream = inTemp; 
    outputStream = outTemp; 
} 

@Override 
public void run() { 
    byte[] buffer = new byte[1024]; 
    int readed; 

    while (true) { 
     try { 
      readed = inputStream.read(buffer); //IN THIS POINT JUMPS TO THE CATCH STATEMENT 
      if (readed > 0) { 
       final byte[] temp = new byte [readed]; 
       System.arraycopy(buffer, 0, temp, 0, readed); 

       /*Shows on UI*/ 
       activity.runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         connectionListener.msgRead(temp); 
        } 
       }); 
      } 
     } catch (IOException e) { 
      connectionListener.onDisconnected("Error when reading: " +e.getMessage()); 
      break; 
     } 
    } 
} 

그래서, 표시 위의 줄에 catch 문으로 이동이 내가 로그 캣에 무엇을 얻을 수 있습니다 :

11-27 09:49:24.438: W/BluetoothAdapter(5297): getBluetoothService() called with no BluetoothManagerCallback 
11-27 09:49:24.438: D/BluetoothSocket(5297): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[46]} 
11-27 09:49:24.458: I/Adreno200-EGL(5297): <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_2.5.5.04.02.02.092.059_msm8960_JB_2.5.5_CL3896081_release_AU (CL3896081) 
11-27 09:49:24.458: I/Adreno200-EGL(5297): Build Date: 06/25/13 Tue 
11-27 09:49:24.458: I/Adreno200-EGL(5297): Local Branch: 
11-27 09:49:24.458: I/Adreno200-EGL(5297): Remote Branch: quic/jb_2.5.5 
11-27 09:49:24.458: I/Adreno200-EGL(5297): Local Patches: NONE 
11-27 09:49:24.458: I/Adreno200-EGL(5297): Reconstruct Branch: AU_LINUX_ANDROID_JB_2.5.5.04.02.02.092.059 + NOTHING 
11-27 09:49:24.528: D/OpenGLRenderer(5297): Enabling debug mode 0 
11-27 09:49:24.658: I/Timeline(5297): Timeline: Activity_idle id: [email protected] time:2279177 
11-27 09:49:25.769: E/BluetoothSocket(5297): IOException while reading the InputStream 
11-27 09:49:25.779: D/onDisconnected(5297): Error when reading: bt socket closed, read return: -1 

답변

0

는 I는 장치 페어링 후 ClientConnectionThread를 설정하라는 해결
0

read()inputStream 앞에있는 것처럼 보입니다. 연결이 완료되었습니다.

The documentation of getInputStream()는 말한다 : 연관된 소켓이

시작에게 ConnectedThreadsocket.connect() 후 반환

연결 될 때까지

[...] 그 스트림에 작업이 IOException이 발생합니다.

synchronized (ClientConnectionThread.this) { 
    GlobalVar.clientConnectionThread = null; 
} 
:
관련 문제