Detect Enable/Disable Bluetooth - android

I made an application to turn on/off bluetooth. To turn on/off i used a switch button. Here is the code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
break;
case BluetoothAdapter.STATE_ON:
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null){
//Device does not support bluetooth
}
else{
bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
}
});
}
}
}
The problem is that if i turn on/off bluetooth from settings and not from my app the switch doesn't change.
I have implemented a broadcast receiver but i can't access the switch from it.
I tried:
bluetoothSwich.setChecked(true)
inside the broadcast receiver but it doesn't work.
Ty
EDIT :
I partially solved the problem with the global switch but to catch the on/off action from settings first i have to click the on/off button from my app at least one time. any suggestion?

To detect the state change of bluetooth you need to add following permission to your AndroidManifest.xml.
<uses-permission android:name="android.permission.BLUETOOTH" />
Use a Local broadcast preferably. You do not need to register it in Manifest . register it at runtime where you need it.(If need throughout the app then register it in Manifest)
private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
// Bluetooth is disconnected, do handling here
}
}
}
};
Runtime register:
LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
Runtime unregister : Don't forget to unregister the broadcast.
LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver);
Static Register:
<receiver
android:name=".FullyQualifiedBroadcastReceiverClassName"
android:enabled="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>

Related

Bluetooth BroadcastReceiver retuns null

I'm learning to code for Android, my first project uses bluetooth so I thought I'd start there. Basically I'm trying to scan for the other available bluetooth device with the press of a button, and display its name in a textview.
I register a BroadcastReceiver (mReceiver) with an ACTION_FOUND filter. I know I'm starting discovery correctly since other devices can see me, but I can't get their names. Debugging through AS seems to show that my instance for mReceiver is null.
public class MainActivity extends AppCompatActivity {
private Scanner_Bluetooth mainBLScanner;
public BroadcastReceiver mReceiver;
public int DISCOVERY_REQUEST = 1;
public static final String[] runtimePermissions = {};
public static final int LOCATION_PERMISSION_IDENTIFIER = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonConnect = (Button) findViewById(R.id.buttonBT);
final TextView tv_name =(TextView)findViewById(R.id.tv_name);
mainBLScanner = new Scanner_Bluetooth(this, 5000, -75);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
mReceiver = new BroadcastReceiver(getApplicationContext());
registerReceiver(mReceiver, filter);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mainBLScanner.Start();
tv_name.setText(mReceiver.getDeviceName());
}
};
buttonConnect.setOnClickListener(listener);
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
#Override
protected void onStop() {
unregisterReceiver(mReceiver);
super.onStop();
}
And this is how I implemented BroadcastReceiver
public class BroadcastReceiver extends android.content.BroadcastReceiver {
private String deviceName = "DUMMY";
private String deviceHardwareAddress;
Context activityContext;
private static final String TAG = "BroadcastReceiver";
public BroadcastReceiver(Context activityContext) {
this.activityContext = activityContext;
}
public String getDeviceName(){
return deviceName;
}
public String getAddress(){
return deviceHardwareAddress;
}
//this detects when bluetooth is on/off
#Override
public void onReceive(Context context, Intent intent) {
final String sAction = intent.getAction();
Log.d(TAG, "start onReceive: " + sAction);
if (sAction.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Toast.makeText(context, "Bluetooth is off", Toast.LENGTH_LONG).show();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Toast.makeText(context, "Bluetooth is turning off", Toast.LENGTH_LONG).show();
break;
case BluetoothAdapter.STATE_ON:
Toast.makeText(context, "Bluetooth is on", Toast.LENGTH_LONG).show();
break;
case BluetoothAdapter.STATE_TURNING_ON:
Toast.makeText(context, "Bluetooth is turning on", Toast.LENGTH_LONG).show();
break;
default:
break;
}
if (BluetoothDevice.ACTION_FOUND.equals(sAction)) {
Log.d(TAG, " Action_Found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context,"Device Found!!",Toast.LENGTH_LONG).show();
this.deviceName = device.getName();
this.deviceHardwareAddress = device.getAddress(); // MAC address
}
}
}}
In my manifest I have both Bluetooth and BluetoothAdmin permissions. Also Coarse & Fine access.

How to detect android headset button click on 4.0 and higher

I am trying to detect Headset button click referring to this
http://android.amberfog.com/?p=415
This is the code I haave tried
public class MainActivity extends Activity {
private IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actvity_main);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
mIntentFilter.setPriority(2147483647);
registerReceiver(mReceiver, mIntentFilter);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
Toast.makeText(MainActivity.this,"Your Message", Toast.LENGTH_LONG).show();
}
abortBroadcast();
}
};
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
All I am trying to do is get a toast message for the button click received , but it is just not getting detected What exactly should be done to detect the button click .
I am testing on a real android device with Android 4.2.1
Have you registered your broadcast receiver in AndroidManifest.xml?
<receiver android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>

How to detect click event of connected Bluetooth peripheral device (Selfie stick)?

I have Selfie stick connected to my phone. I am able to find device ID using below code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Toast.makeText(getApplicationContext(), "ACTION_ACL_CONNECTED" + device, Toast.LENGTH_LONG).show();
}
}
};
My question is how I can detect button press/click event of this connected peripheral device?
Help in form of code snippet/tutorial/comments is highly appreciable.
Thanks!!!
EDIT:
When I press button of Selfie stick Volume + button listen to the event
I found the answer. It was very simple. Just override onKeyDown() method of Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return super.onKeyDown(keyCode, event);
}
Here keyCode is the event name returned.
I have made slight modifications in your code. Please see if its helpful
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter a_filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, a_filter);
IntentFilter b_filter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON);
**b_filter.setPriority(1000);**
this.registerReceiver(mReceiver, b_filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Toast.makeText(getApplicationContext(), "ACTION_ACL_CONNECTED" + device, Toast.LENGTH_LONG).show();
}
if (!Intent.ACTION_CAMERA_BUTTON.equals(action)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
};
Using accessibility service, You can achieve auto-click.
Answer explained here, May be it's helpful to you !

Not able to scan bluetooth devices

I am developing an app which scans the bluetooth devices and list them all. My requirement is that I have to scan for devices as soon as application starts..Now my problem is when i run the app for the first time it only turns on the bluetooth but does not scan for devices..
I can see the bluetooth icon on screen but in log cat getState() method of the BluetoothAdapter shows state as STATE_OFF.
Please anyone help me about this issue ??
Here is my code snippet
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
Set<String> BTList;
ArrayAdapter<String> BTAdapter;
private ListView listView;
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listView = (ListView) findViewById(R.id.listView1);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null)
Toast.makeText(this, "Devices does not support Bluetooth",
Toast.LENGTH_SHORT).show();
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if(bluetoothAdapter.isEnabled()) {
if(bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}
bluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTAdapter.add(device.getName() + "\n" + device.getAddress());
BTAdapter.notifyDataSetChanged();
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
BTAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1);
listView.setAdapter(BTAdapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
//if(bluetoothAdapter != null)
// bluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
}
Check in your AndroidManifest.xml file, if you have these below entries
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

AIRPLANE_MODE action not receiving

android Airplane mode not showing logs
my code is as below
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(ACTION_AIRPLANE_MODE);
registerReceiver(mBroadcastReceiver, intentFilter);
// AppRater.app_launched(new WeakReference<Activity>(this));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Mass", "Action " + intent.getAction());
if (intent.getAction().equals(ACTION_AIRPLANE_MODE)) {
mHandlerRedrawUI.sendEmptyMessage(UPDATE_VISIBILITY);
}
}
};
private static final int UPDATE_VISIBILITY = 1;
private static final String ACTION_AIRPLANE_MODE = "android.intent.action.AIRPLANE_MODE";
Handler mHandlerRedrawUI = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == UPDATE_VISIBILITY) {
}
}
};
}
I just turned on Airplan mode and turned off not getting my log receicer
like
<receiver android:name="com.example.Bootreciever">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
Sometime we should think outside box :D :P
I was connected my device through wifi and testing, when I was enabling Airplane mode it was getting disconnected so I was not getting logs, The code is fine and its works as I needed

Categories

Resources