Android Enable/ Disable Bluetooth - android

I have a code, in my app, where a button press turn on bluetooth on and off.
I want to change the background of this button to green and red, when the bluetooth is either on or off. I did google answers for it and there is a stackoverflow post similar to it and the way he mentioned is not working. I registered a receiver and have a switch case as usual, where I mentioned this button color change and it s not working.
Infact the log.d in the receivers are not even being shown up in the terminal of android studio.
THE CODE IS NOT ABOUT HOW TO IMPLETMENT THE COLOR, BUT ACCESSING THE STATE CHANGE OF BLUETOOTH FROM BROADCAST RECEIVER
public void enableDisableBT(){
if(mBluetoothAdapter == null) {
Log.d(TAG, "enableDisableBT: Does not have BT capabilities");
Toast.makeText(getApplicationContext(),"No Bluetooth Capability", Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT");
//btnONOFF.setBackgroundColor(Color.GREEN); // Since bluetooth is NOT enabled, it enables bluetotoh and sets background color to green
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT");
mBluetoothAdapter.disable();
btnONOFF.setBackgroundColor(Color.RED);// Since bluetooth is enabled, it disables bluetotoh and sets background color to green
incomingMessages.setText("Incoming Messages");
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// when discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)){
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,mBluetoothAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
//Log.d(TAG, "mBroadcastReceiver1: STATE ON");
btnONOFF.setBackgroundColor(Color.GREEN);
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};

You need to declare a BroadcastReceiver in your manifest to listen to Bluetooth state. This article sums it up well: https://droidhat.com/broadcast-receiver-using-change-in-bluetooth-status
1)
/**
* A receiver that listens to Bluetooth getting turned on.
*/
public class BluetoothReceiver extends BroadcastReceiver {
#Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int state;
switch (action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
if (state == BluetoothAdapter.STATE_ON) {
// change my button color
}
}
}
}
2)
<receiver
android:name="com.myapp.BluetoothReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
</intent-filter>
</receiver>

Related

Bluetooth enable time

I am using the below code as per requirement from client to internally enable Bluetooth and disable it when exit the application.
if (!bluetoothAdapter.isEnabled()) {
MMLogger.logInfo(MMLogger.LOG_BLUETOOTH, "BluetoothSyncController - Bluetooth was OFF, so Turn it ON");
bluetoothAdapter.enable();
try {
Thread.sleep(WAIT_FOR_SOMETIME_TO_START_BLUETOOTH);
} catch (InterruptedException ignore) {
}
MMLogger.logInfo(MMLogger.LOG_BLUETOOTH, "BluetoothSyncController - Bluetooth turned ON");
}
IS there any standard time for WAIT_FOR_SOMETIME_TO_START_BLUETOOTH ? I mean any documentation ?
You might try this answer. There seem to be some standard bluetooth events and handlers out there.
From that source: There are events that your activity can manage such as
STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF
and you can catch these with a BroadcastReciever. First you want to make sure that you grant permissions for bluetooth inside of your manifest with:
<uses-permission android:name="android.permission.BLUETOOTH" />
Then you can create a custom broadcast receiver that has the following onReceive():
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch(state) {
case BluetoothAdapter.STATE_OFF:
..
break;
case BluetoothAdapter.STATE_TURNING_OFF:
..
break;
case BluetoothAdapter.STATE_ON:
..
break;
case BluetoothAdapter.STATE_TURNING_ON:
..
break;
}
}
}
Then instead of making a thread to wait you can have a receive event trigger the code you want to run. For more info on using a BroadcastReciever, see the link I provided or go straight to the android documentation.

App asks for USB permission on every Phone restart

I'm using an USB-Receiver to handle the Communication with a Temperature Sensor attached via USB to the Phone.
Everything is working fine so far, but if i restart the Phone, the App throws an USB-Permission pop-up directly after restarting, even if there isn't any USB-Device attached to the Phone at that Moment.
Has anyone an Idea of what's causing this strange Problem?
[ EDIT: I'm Sorry, the App isn't asking for USB Permission, the popup asks if i want to Open the app if "this device is connected" but there's obviously no device attached.]
Here is the Code of the USB-Receiver:
//Initial USB Settings Receiver
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
// is usb permission has been granted, try to open a connection
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
Constants result = mcp2221.open();
if (result != Constants.SUCCESS) {
//nothing by now
} else {
openConnectionToMCP2221();
}
}
}
}
}
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
// close the connection and release all resources
closeAllResources();
// leave a bit of time for the COM thread to close
try {
Thread.sleep(20);
}catch(InterruptedException e){e.printStackTrace();}
mcp2221Comm = null;
Toast.makeText(getApplicationContext(), "Device detached",
Toast.LENGTH_SHORT).show();
}
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
Toast.makeText(getApplicationContext(), "Device attached",
Toast.LENGTH_SHORT).show();
mStopUSBThread=false;
// only try to connect if an MCP2221 is attached
if (device.getVendorId() == MCP2221_VID && device.getProductId() == MCP2221_PID) {
Constants result = mcp2221.open();
switch (result) {
case SUCCESS:
openConnectionToMCP2221();
break;
case CONNECTION_FAILED:
Toast.makeText(getApplicationContext(), "ERROR: connection failed", Toast.LENGTH_SHORT).show();
break;
case NO_USB_PERMISSION:
Toast.makeText(getApplicationContext(), "ERROR: no USB permission", Toast.LENGTH_SHORT).show();
mcp2221.requestUsbPermission(mPermissionIntent);
break;
default:
break;
}
}
}
}
}
};
And here is the onCreate() part:
//USB Connection
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbReceiver, filter);
//Checking if theres a Device already connected
.......
Got it!
It was an
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
</intent-filter>
that was declared in AndroidManifest.xml under <activity>.
I don't fully understand, why it caused this Bug, but removing it kept the functionality of my App while getting rid of the Problem.
Only 'negative' aspect might be, that now the App doesn't ask to open if the Sensor is attached to the phone.

Detecting State changes made by Bluetooth adapter through a background service

I have been trying to develop a service that detects BLE devices in the background. The background service runs seemlesly when bluetooth is enabled. However when bluetooth is not running i turn on bluetooth via
bluetoothAdapter.enable();
In order to listen to changes made by the bluetooth adapter i declare a broadcastreceiver in my service in the onCreate() method like this:
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
My broadcast receiver looks like this:
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.v("Broadcast called", "in service");
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED))
{
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Log.v("Bluetooth state", "Off");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.v("Bluetooth state", "Turning Off");
break;
case BluetoothAdapter.STATE_ON:
Log.v("Bluetooth state", "Turned On");
scanLeDevice(true) ;
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.v("Bluetooth state", "Turning On");
break;
}
}
}
};
the adapter.enable() call turns bluetooth on successfully however the problem i am facing here is that the onReceive method in the receiver never gets triggered as a result of which i cannot run and scan for BLE devices.
When i do these exact same steps in an activity everything works perfectly.
At first i thought that the onReceive is not triggered because the service is in a background thread. So i also triggered the service via a WakefullBroadcastReceiver but that made no change in behavior.
I would like to understand what i am doing wrong here and some help in solving this.

Battery changed receiver not working

I want to react to the charging state in my app.
I registered the receiver for it in onCreate()
registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
the receiver looks like that:
private BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
String test = Integer.valueOf(plugged).toString();
Toast.makeText(getApplicationContext(), test,
Toast.LENGTH_LONG).show();
}
};
but even if the device is plugged in the plugged variable is 0. Any idea how to fix that?
You could try to use BatteryManager.EXTRA_STATUS. The BatteryManager.EXTRA_PLUGGED can be used if you want more details about the type of power source I believe.
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intentResult = registerReceiver(null, filter);
int state = intentResult.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
switch (state) {
case BatteryManager.BATTERY_STATUS_CHARGING:
case BatteryManager.BATTERY_STATUS_FULL:
//charging
break;
default:
//not charging
}

Bluetooth Server and BroadCastReceiver

My application holds an open bluetooth server socket with a specific UUID, in order for another device to connect and transfer files. I'm a bit confused regarding the BroadcastReceiver.
In my class which extends Activity, I want to check the state of the bluetooth adapter. But my BroadcastReceiver is never triggered. I tried using the 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 the states:
The state STATE_ON is this only fired off when the bluetooth is turned on during runtime? Or can I start my application with bluetooth turned on, and this event will be fired off? Cause I want to start the method btCom.startServer() if bluetooth is turned on
I also read that I need to register the broadcast receiver in my Manifest file, how can I do so if the BroadcastReceiver is in a class which extends Activity? If I had this BroadcastReceiver in a separate class I would do it like this
Say for instace that my Package Name was com.workbench and my Class name was BluetoothReceiver
The Manifest would look something like this:
<receiver android:name="com.workbench.BluetoothReceiver"></receiver>
The broadcast action BluetoothAdapter.ACTION_STATE_CHANGED is sent when the state of the bluetooth adapter changes. You will only see this when the state of the adapter is changed.
You can check the current state of the bluetooth adapter by calling BluetoothAdapter.isEnabled().
You only need to register the BroadcastReceiver in your manifest if you want to get the broadcast Intent when your application is not running. The way you have implemented the BroadcastReceiver (as an anonymous class) it isn't possible to register it in the manifest.

Categories

Resources