mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, "不支持蓝牙", Toast.LENGTH_SHORT).show(); } else if (!mBluetoothAdapter.isEnabled()) { Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT); }
private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0); switch (state) { case BluetoothAdapter.STATE_TURNING_ON: Toast.makeText(MainActivity.this, "Bluetooth正在打开", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_ON: Toast.makeText(MainActivity.this, "Bluetooth已打开", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_TURNING_OFF: Toast.makeText(MainActivity.this, "Bluetooth正在关闭", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_OFF: Toast.makeText(MainActivity.this, "Bluetooth已关闭", Toast.LENGTH_SHORT).show(); break; } } };
@Override protected void onResume() { super.onResume(); registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); } @Override protected void onStop() { super.onStop(); unregisterReceiver(receiver); }