Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android receive callback when bluetooth device is paired/connected by the system automatically?

Is there any way to receive a callback when Android automatically pairs/connects to a bluetooth device, for instance my car, and not having the app already started/open (some kind of broadcast)? I have had thoughts about a service that periodically scans for devices and sees if they are already bonded, but that feels ineffective as Android already does this: it will automatically connect to for instance my car when I am in range. The idea is to start a specific job when I am in range of my car, and stop the job when I am out of range of my car, without having to start the app or have it open.

My initial thought was that there should be some kind of broadcast one could register to, to know when the device is "connected", and in that listener just start the job for some time or until the device is "disconnected". Note that having your phone in your pocket and not taking it up is a necessity. I have only seen examples that does this if the app is already open, by listening on state changes. Is this possible to not have the app open and only be "event driven" and listen on broadcasts?

like image 769
Simon Zettervall Avatar asked Mar 14 '17 12:03

Simon Zettervall


1 Answers

Try the following code:

IntentFilter actionChangeFilter = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        mContext.registerReceiver(btDeviceConnectChangedReceiver, actionChangeFilter);
like image 123
Duna Avatar answered Sep 29 '22 03:09

Duna