Getting Started

Recommended Step:

Download the SweetBlue Toolbox app here. Use the Toolbox to find the settings that work best for the device you're trying to connect to. Once you find settings that work well for you, you can export them to a json file, with which you can then import into SweetBlue (Using new BleManagerConfig(jsonData)).

  • Modify your app's build.gradle file to pull SweetBlue down from our maven server, and add the dependency to your project:


repositories {
    ...
    maven {
        url "https://archiva.sweetblue.io/repository/internal"
    }
}

dependencies { ... implementation "com.idevicesinc:sweetblue:3.0.2" }

  • Create a file called sweetblue_api_key.txt in your app's assets directory. Paste your API key into this new file. Without this file, you will not be able to use SweetBlue in your app. If you try to instantiate BleManager without it, a RuntimeException will be thrown.
  • SweetBlue provides a helper class to handle all the permissions, and turning things on for you. If you decide to use this class, you must use it in an Activity, as it shows dialogs.
  • The following example shows how to use the BleSetupHelper class, along with starting a scan, connecting to the first device seen, then reading it's battery level.


BleManagerConfig config = new BleManagerConfig();
BleManager manager = BleManager.get(this, config);
BleSetupHelper.runEnabler(manager, this, result -> 
{
    if (result.getSuccessful()) 
    {
        // Do whatever you want to do with Bluetooth now.
        scanThenConnectThenRead(manager);
    }
});


private void scanThenConnectThenRead(BleManager manager)
{
    // Set a discovery listener to be notified when a device is discovered
    manager.setListener(discoveryEvent ->
    {
        if (discoveryEvent.was(LifeCycle.DISCOVERED)
        {
            // Stop scanning now, so we don't end up connecting to every device we see.
            manager.stopScan();
            discoveryEvent.device().connect(connectEvent ->
            {
                if (connectEvent.wasSuccess())
                {
                    BleRead read = new BleRead(Uuids.BATTERY_SERVICE, Uuids.BATTERY_LEVEL);
                    read.setReadWriteListener(readEvent -> 
                    {
                        if (readEvent.wasSuccess())
                            Log.i("", "Battery level is " + readEvent.data_byte() + "%");
                    });
                    connectEvent.device().read(read);
                }
                else
                {
                    if (!connectEvent.isRetrying())
                    {
                        Log.e("MyApp", "Device failed to connect. Fail Event: " + connectEvent.failEvent());
                    }
                }
            }
        }
    }
    // Start a scan
    manager.startScan();
}