PendingIntent Scan

This type of scan is very useful if you need to have a scan running pretty much at all times, including when your app is not running. This will wake up your app when the android device has found bluetooth device(s) in range.

PLEASE NOTE THAT THIS TYPE OF SCAN IS ONLY AVAILABLE IN ANDROID 8 AND UP

To use this type of scan, it will require a bit more work than a typical scan.

First, you need to create a class which extends BroadcastReceiver.


public class MyScanReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // Get the instance of BleManager
        BleManager mgr = BleManager.get(context);
        // SweetBlue provides a convenience method to convert the Intent instance to a list of BleDevice instances.
        List deviceList = mgr.getDevices(intent);
        // Now do what you need to do with the discovered devices
    }
}

This receiver class must also be registered within your AndroidManifest.xml file like so:


    <application>
        <receiver android:name="com.myapp.MyScanReceiver" >
            <intent-filter>
                <action android:name="com.myapp.ACTION_FOUND" />
            </intent-filter>
        </receiver>
    </application>

You will need a PendingIntent instance to start and stop the scan. You can create it like so:


    PendingIntent pIntent = PendingIntent.getBroadcast(activity, 42, new Intent(activity, TestReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);

NOTE: You will need this PendingIntent instance to stop the scan. NOTE 2: Using this type of scan will leave a scan task in SweetBlue's task queue. This won't affect other operations, it's there basically so the system knows a "scan" is in progress.

Now, to execute the scan, just do the following:


    ScanOptions options = new ScanOptions();
    options.withPendingIntent(pIntent);
    // You may want to also set the defaultNativeScanFilterList option in BleManagerConfig to have android filter the
    // devices for you, as SweetBlue won't have access to the devices to filter them for you.
    bleManager.startScan(options);

To stop the scan, simply do:


    bleManager.stopScan(pIntent);