<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="https://devzone.nordicsemi.com/cfs-file/__key/system/syndication/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/f/nordic-q-a/2995/having-android-reconnect-to-a-bonded-peripheral-without-user-interaction</link><description>I&amp;#39;ve read the Robin Heydon book and bits of the Core 4.0 spec and I&amp;#39;m still confused as to how an Android phone with my app installed is supposed to reconnect to my peripheral to which is has previously connected and bonded. 
 Suppose my peripheral is</description><dc:language>en-US</dc:language><generator>Telligent Community 13</generator><lastBuildDate>Sat, 24 Sep 2022 15:45:34 GMT</lastBuildDate><atom:link rel="self" type="application/rss+xml" href="https://devzone.nordicsemi.com/f/nordic-q-a/2995/having-android-reconnect-to-a-bonded-peripheral-without-user-interaction" /><item><title>RE: Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/thread/387756?ContentTypeID=1</link><pubDate>Sat, 24 Sep 2022 15:45:34 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:3d0a296f-7329-41b2-9854-ad8e04c49411</guid><dc:creator>Zami</dc:creator><description>&lt;p&gt;I know this is an old post but since no one really answered it I&amp;#39;ll show what I did. This is written in Kotlin btw.&lt;/p&gt;
&lt;p&gt;I don&amp;#39;t know if this is the best solution but it works for my case. I wanted the app to auto connect to a peripheral device that&amp;#39;s previously bonded and advertising.&lt;/p&gt;
&lt;p&gt;I created a fragment that runs the code below. The fragment is part of a fragment container and is part of the the MainActivity layout.&lt;/p&gt;
&lt;p&gt;It basically registers a bluetooth broadcast receiver to watch the state. When bluetooth is turned on, it reads through the bonded devices list and if one of the devices has the name of your device then it will call Nordic&amp;#39;s autoconnect function for the device.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;class DeviceMonitorFragment : Fragment() {
    private var _fragmentDeviceMonitorBinding: FragmentDeviceMonitorBinding? = null
    private val fragmentDeviceMonitorBinding get() = _fragmentDeviceMonitorBinding!!

    /**
     * Checks the bluetooth state and try to auto connect the
     * ble device when bluetooth is turned on and active.
     * The device should connect if it is on and bonded.
     * Otherwise the user will have to manually connect it from
     * the scanner fragment or through the Android Bluetooth settings.
     */
    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (BluetoothAdapter.ACTION_STATE_CHANGED == action) {
                when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) {
                    BluetoothAdapter.STATE_TURNING_OFF,
                    BluetoothAdapter.STATE_OFF,
                    BluetoothAdapter.STATE_TURNING_ON,
                    -&amp;gt; {
                    }
                    BluetoothAdapter.STATE_ON -&amp;gt; {
                        // Attempt to connect device
                        autoConnectDeviceIfMatch(requireContext())
                    }
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        _fragmentDeviceMonitorBinding = FragmentDeviceMonitorBinding.inflate(inflater, container, false)
        return fragmentDeviceMonitorBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        /** Register broadcast receiver to watch bluetooth state */
        requireContext().registerReceiver(mReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED))

        /** Attempt to connect device if bluetooth is enabled and device is advertising */
        autoConnectDeviceIfMatch(requireContext())
    }

    /**
     * Connects to the ble device if it is bonded and the
     * name matches our device name
     *
     * @param context
     */
    @SuppressLint(&amp;quot;MissingPermission&amp;quot;)
    fun autoConnectDeviceIfMatch(context: Context){
        val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        if(manager.adapter.isEnabled){
            val devices = manager.adapter.bondedDevices
            devices.forEach { device -&amp;gt;
                if (device.bondState == BluetoothDevice.BOND_BONDED &amp;amp;&amp;amp; device.name == context.getString(R.string.app_name)) {
                    DataShared.device.connect(context, device)
                    return@forEach // exit on match
                }
            }
        }
    }

    override fun onDestroy() {
        requireContext().unregisterReceiver(mReceiver)
        _fragmentDeviceMonitorBinding = null
        super.onDestroy()
    }
}&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;The code below would be located in a device manager of sorts. Similar to the Blinky example for Android.&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;    /**
     * Connect to the given peripheral
     * (Primarily for use by the auto-bonding)
     *
     * @param target the target device
     */
    @SuppressLint(&amp;quot;MissingPermission&amp;quot;)
    fun connect(context: Context, target: BluetoothDevice) {
        if (_bleDevice == null) {
            _bleDevice = target
            val logSession = Logger
                .newSession(context, null, target.address, target.name)
            _bleDeviceManager.setLogger(logSession)
        }
        
        autoConnect()
    }

    /**
     * Reconnects to previously connected device
     * If this device was not supported, its services were cleared on disconnection, so
     * reconnection may help
     */
    private fun autoConnect() {
        if (_bleDevice != null) {
            _bleDeviceManager.connect(_bleDevice!!)
                .retry(3, 100)
                .useAutoConnect(true)
                .enqueue()
        }
    }&lt;/pre&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/thread/11325?ContentTypeID=1</link><pubDate>Wed, 19 Nov 2014 07:49:17 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:2fbcc17d-4a87-4037-8377-b8f46c33c7cc</guid><dc:creator>wen</dc:creator><description>&lt;p&gt;Excuse me , did you solve the problem ? I have the same question about auto reconnect when BLE device disconnect and come back in range and starts advertising.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/thread/11329?ContentTypeID=1</link><pubDate>Mon, 07 Jul 2014 20:56:54 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:a462aaa8-bef4-4b5d-96cd-990747b7d49a</guid><dc:creator>Eliot Stock</dc:creator><description>&lt;p&gt;Here&amp;#39;s some interesting Javadoc from BluetoothGatt.connect() method (not the public one) in the AOSP source, which rather implies that subsequent connections are to be made programmatically:&lt;/p&gt;
&lt;p&gt;The autoConnect paramter determines whether to actively connect to the remote device, or rather passively scan and finalize the connection when the remote device is in range/available. Generally, the first ever connection to a device should be direct (autoConnect set to false) and subsequent connections to known devices should be invoked with the autoConnect parameter set to true.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/thread/11328?ContentTypeID=1</link><pubDate>Fri, 04 Jul 2014 14:21:51 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:6b813ca6-d47d-4d23-a0bb-b398e83484bd</guid><dc:creator>Eliot Stock</dc:creator><description>&lt;p&gt;Thanks. Was aware of that autoConnect param but in my experience passing true there does NOT mean that a peripheral that&amp;#39;s been disconnected for days then reappears will be reconnected.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/thread/11327?ContentTypeID=1</link><pubDate>Fri, 04 Jul 2014 12:35:38 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:8b304004-2bc9-4987-9f2d-0ebbf2a50794</guid><dc:creator>leo</dc:creator><description>&lt;p&gt;As far as i know it scans with a callback if you start startLEScan, but there is the possibility to set a flag for an auto-connect if the device is available:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second parameter is the autoConnect parameter [1] (boolean indicating whether to automatically connect to the BLE device as soon as it becomes available). So, i guess it scans in the background without starting it (otherwise, it wouldn&amp;#39;t be possible to auto reconnect)&lt;/p&gt;
&lt;p&gt;Was this your question?
cheers&lt;/p&gt;
&lt;p&gt;[1] &lt;a href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#connect"&gt;developer.android.com/.../bluetooth-le.html&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Having Android reconnect to a bonded peripheral without user interaction</title><link>https://devzone.nordicsemi.com/thread/11326?ContentTypeID=1</link><pubDate>Fri, 04 Jul 2014 12:19:55 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:3806dd18-a135-4074-879d-5b4992dd36ba</guid><dc:creator>gootoomoon</dc:creator><description>&lt;p&gt;the same question like you&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item></channel></rss>