Enabling Bluetooth and tracking the adapter state


BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver bluetoothState = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String prevStateExtra = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
String stateExtra = BluetoothAdapter.EXTRA_STATE;
int state = intent.getIntExtra(stateExtra, −1);
int previousState = intent.getIntExtra(prevStateExtra, −1);
String tt = "";
switch (state) {
case (BluetoothAdapter.STATE_TURNING_ON) : {
tt = "Bluetooth turning on"; break;
}
case (BluetoothAdapter.STATE_ON) : {
tt = "Bluetooth on";
unregisterReceiver(this);
break;
}
case (BluetoothAdapter.STATE_TURNING_OFF) : {
tt = "Bluetooth turning off"; break;
}
case (BluetoothAdapter.STATE_OFF) : {
tt = "Bluetooth off"; break;
}
default: break;
}
Toast.makeText(this, tt, Toast.LENGTH_LONG).show();
}
};
if (!bluetooth.isEnabled()) {
String actionStateChanged = BluetoothAdapter.ACTION_STATE_CHANGED;
String actionRequestEnable = BluetoothAdapter.ACTION_REQUEST_ENABLE;
registerReceiver(bluetoothState,
new IntentFilter(actionStateChanged));
startActivityForResult(new Intent(actionRequestEnable), 0);
}

Comments

Popular posts from this blog

Bluetooth Data Transfer Example

How to Create & Extract tar.gz and tar.bz2 Files in Linux