工作完成后无法停止工作者(ListenableWorker)任务

时间:2019-08-26 11:03:23

标签: android worker

我似乎找不到停止我的工作任务的正确方法。我在.set(Result.success());上调用ResolvableFuture<Result>,但是在我的课程中它从未触发onStopped(),并且其他订阅的回调似乎仍在我的工作程序中处于活动状态。

  • 我的工人启动并尝试查找特定的BLE设备
  • 它已连接到该设备,并尝试通过Result.success()退出
  • 如果工作时间超过3分钟,请尝试退出。

在我连接到BLE设备后调用Result.success()后,它仍将在onConnectionStateChange函数中保留对connectGatt()的有效引用。

即使在操作系统强行停止我的工作人员之后,它似乎都没有调用onStopped(),因为我从不记得在日志中看到过它。

即使在创建新工作线程之后,我仍然可以使用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");
    }

}

1 个答案:

答案 0 :(得分:2)

请注意,ListenableWorker.onStopped()方法仅在取消工作程序或系统抢占任务时才调用。如果工作人员已成功完成,则不会调用onStop()onStop() documentation tells

  

当告诉该Worker停止时,调用此方法。 ...   这可能是由于用户明确取消信号而发生的,   或因为系统已决定抢占该任务。 ...

有时,即使工作程序成功完成,也可以调用onStop()回调,但是将来会更正a bug。看一下这篇文章:Why is Android Worker finishing successfully and calling onStopped()