无法取得在Android的蓝牙适配器(Can't get bluetooth Adapter

2019-10-17 09:23发布

我试图实现了Android样本中给出的蓝牙聊天的例子。 我拥有的Android 4.1版本上运行一个糖豆设备上运行它。

该应用程序只是强制关闭。 的发射活动的发射活动代码的一部分是这样的。

当我注释的行“mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();” 应用程序不强制关闭。 和所有的吐司消息也被显示,其不与线未注释

    private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;


@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

     Toast.makeText(getApplicationContext(),"BluetothChat oncreate()", Toast.LENGTH_LONG).show();
    if(D) Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    setContentView(R.layout.main);

    // Get local Bluetooth adapter
  try {     

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

   //}
    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }     
 } catch (Exception e) {
       Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show(); 

 }
}

@Override
public void onStart() {



    Toast.makeText(getApplicationContext(),"BluetothChat onstart()", Toast.LENGTH_LONG).show();
    super.onStart();
    if(D) Log.e(TAG, "++ ON START ++");

    // If BT is not on, request that it be enabled.
    // setupChat() will then be called during onActivityResult
    try {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else {
            if (mChatService == null) {
                setupChat();
            }
        }
    } catch (Exception e) {
     Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show(); 
    }


}
文章来源: Can't get bluetooth Adapter in Android