Thursday, 29 August 2019

Can't stop worker (ListenableWorker) task when work has finished

I can't seem to find the correct way to stop my worker task. I'm calling .set(Result.success()); on my ResolvableFuture<Result>, but it never triggers onStopped() in my class and other subscribed callbacks seem to still be active inside my worker.

  • My worker starts and tries to find specific BLE device
  • It connects to that device and tries to exit with Result.success()
  • Tries to exit if worker has run more than 3 minutes.

After calling Result.success() after I connected to BLE device it will still hold a active reference to onConnectionStateChange inside connectGatt() function.

It doesn't even seem to call onStopped() even after OS forcibly stops my worker, as I don't ever remember to have seen it in logs.

Even after a new worker is created I still get updates inside the old worker with onConnectionStateChange

package test;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.concurrent.futures.ResolvableFuture;
import androidx.work.ListenableWorker;
import androidx.work.WorkerParameters;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.List;

import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;
import static android.os.Build.VERSION_CODES.M;

public class BluetoothScanWorker extends ListenableWorker  {

    private String TAG = "BluetoothScanWorker";
    private BluetoothAdapter bluetoothAdapter;
    private ResolvableFuture<Result> mFuture;


    public BluetoothScanWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public ListenableFuture<Result> startWork() {
        mFuture = ResolvableFuture.create();

        Log.d(TAG ,"startWork()");

        if (Build.VERSION.SDK_INT >= M) {
            ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
            List<ScanFilter> filters_v2 = new ArrayList<>();
            ScanFilter scanFilter = new ScanFilter.Builder()
                    .setDeviceAddress("B8:27:EB:B9:5C:FC")
                    .build();
            filters_v2.add(scanFilter);
            BluetoothManager bluetoothManager =
                    (BluetoothManager) this.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
            bluetoothAdapter = bluetoothManager.getAdapter();
            bluetoothAdapter.getBluetoothLeScanner().startScan(filters_v2, settings, leScanCallback); // Scan for every BLE device matching my filter

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    endWork();
                }
            }, 3*60*1000); // End worker after 3 minutes
        }
        return mFuture;
    }


    private void endWork(){
        if (Build.VERSION.SDK_INT >= M) {
            Log.d(TAG, "END WORK");
            bluetoothAdapter.getBluetoothLeScanner().stopScan(leScanCallback);
            mFuture.set(Result.success());
        }
    }


    @RequiresApi(M)
    private ScanCallback leScanCallback = new ScanCallback() { // Called when I find my BLE device
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            Log.d(TAG ,"onScanResult: " + result.getDevice().toString());
            bluetoothAdapter.getBluetoothLeScanner().stopScan(this);
            result.getDevice().connectGatt(getApplicationContext(), true, new BluetoothGattCallback() { // Connect to my BLE device
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                    if (newState == BluetoothProfile.STATE_CONNECTED) {
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            Log.d(TAG ,"GATT connected successfully");
                            endWork();
                        }
                    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                        Log.d(TAG ,"GATT disconnected");
                        endWork();
                    }

                }
            },TRANSPORT_LE);

        }
    };


    @Override
    public void onStopped() {
        Log.d(TAG, "Work service stopped");
    }

}



from Can't stop worker (ListenableWorker) task when work has finished

No comments:

Post a Comment