2016-06-03 3 views
0

мой ListeningThread замораживает поток пользовательского интерфейса активности барометра, хотя он не должен. Я понятия не имею, почему это происходит. Помощь нужна :)Android: прослушивающая нить Bluetooth блокирует поток пользовательского интерфейса

Это мой ListeningThread:

public class ListeningThread extends Thread { 

String TAG = "bluetoothThread"; 

private final BluetoothServerSocket bluetoothServerSocket; 
BluetoothAdapter bl; 

public ListeningThread(BluetoothAdapter bluetoothAdapter, String appName) { 
    BluetoothServerSocket temp = null; 
    bl = bluetoothAdapter; 
    try { 
     temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(appName, Constants.MY_UUID_SECURE); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    bluetoothServerSocket = temp; 
} 

public void start() { 
    Log.d(TAG, "ListeningThread running"); 
    BluetoothSocket bluetoothSocket; 
    //This will block while listening until a BluetoothSocket is returned or an exception occurs 
    while (true) { 
     try { 
      bluetoothSocket = bluetoothServerSocket.accept(); 
      Log.d(TAG, "ListeningThread connected"); 
     } catch (IOException e) { 
      break; 
     } 
     // If a connection is accepted 
     if (bluetoothSocket != null) { 

      // Manage the connection in a separate thread 

      try { 
       bluetoothServerSocket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      break; 
     } 
    } 
} 

// Cancel the listening socket and terminate the thread 
public void cancel() { 
    try { 
     bluetoothServerSocket.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
} 

И это деятельность, используя нить и замораживания:

public class BarometerActivity extends AppCompatActivity { 

BluetoothAdapter bluetoothAdapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_barometer); 
    if (SingletonBluetoothAdapter.bluetoothAdapter == null) { 
     SingletonBluetoothAdapter.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    } 
    bluetoothAdapter = SingletonBluetoothAdapter.bluetoothAdapter; 

    ListeningThread t = new ListeningThread(bluetoothAdapter, getString(R.string.app_name)); 
    t.start(); 
} 

} 

Я уверен, что проблема где-то в преддверии метода потока. Я попытался окружить этот метод комментарием, и тогда все работает нормально.

ответ

Смежные вопросы