My application stores an open bluetooth server server with a special UUID so that another device can connect and transfer files. I am a little confused regarding BroadcastReceiver .
In my class that extends Activity , I want to check the status of the bluetooth adapter. But my BroadcastReceiver never works. I tried using BroadcastReceiver this way:
public class MainClass extends Activity { public void onCreate(Bundle b) { super.onCreate(b); IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mReceiver, filter); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); Log.w("BroadcastReceiver: ", "Inside!"); if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_OFF: Log.d("Bluetooth Receiver", "State-off"); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); break; case BluetoothAdapter.STATE_TURNING_OFF: Log.d("Bluetooth Receiver", "State turning off"); break; case BluetoothAdapter.STATE_ON: Log.d("Bluetooth Receiver", "State-on"); btCom = new BluetoothCommunicator(MainClass.this, lastCases, nist); btCom.startServer(); break; case BluetoothAdapter.STATE_TURNING_ON: Log.d("Bluetooth Receiver", "State turning on"); break; } } } }; }
I have a question regarding states:
- Is the STATE_ON status disabled only when bluetooth is turned on during operation? Or can I launch the application with bluetooth turned on and this event will be fired? Cause I want to run the
btCom.startServer() method if Bluetooth is turned on.
I also read that I need to register a broadcast receiver in my manifest file, how can I do this if BroadcastReceiver is in a class that extends Activity? If I had this BroadcastReceiver in a separate class, I would do it like this:
Say my package name was com.workbench and my class name was BluetoothReceiver
The manifest will look something like this:
<receiver android:name="com.workbench.BluetoothReceiver"></receiver>
source share