January 2013
Intermediate to advanced
408 pages
9h 23m
English
If your application uses Bluetooth connectivity, it is useful to know whether the user has just turned on Bluetooth, or just turned it off. This recipe shows how to monitor the state of Bluetooth on the device. For example, if you are writing a service that uses Bluetooth in the background, you need to closely monitor the state of the Bluetooth and start or stop your service appropriately.
To monitor the state of Bluetooth, create a Java class that extends the BroadcastReceiver base class, like this:
package net.learn2develop.turnonbluetooth; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyBTBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int state = intent.getExtras().getInt(BluetoothAdapter.EXTRA_STATE); switch (state) { case BluetoothAdapter.STATE_OFF: Toast.makeText(context, "Off", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_TURNING_OFF: Toast.makeText(context, "Turning Off", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_ON: Toast.makeText(context, "On", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_TURNING_ON: ...Read now
Unlock full access