ScanCallback leScanCallback 在 15 到 30 秒后终止

问题描述

我正在使用 Android BLE 库来检测 BLE 标签。回调成功并返回BLE设备名称RSSI值。只要应用在 UI 线程上运行,扫描也会无限期地继续。

但是,当我关闭应用程序时,扫描会停止,这是意料之中的。但是,我想继续在后台扫描。我已阅读使用前台服务。我已经实现了以下代码

这是我的服务,我也尝试将 runnable 放在 start 命令中。但是,回调仍会在 15 到 30 秒后自行终止。为什么回调只在作为前台服务运行时才终止?

BluetoothManager btManager;
BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;

private notificationmanagerCompat notificationmanager;
private static final String T

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG,"onCreate");

    btManager = (BluetoothManager)getSystemService(Context.BLUetoOTH_SERVICE);
    btAdapter = btManager.getAdapter();
    btScanner = btAdapter.getBluetoothLeScanner();

    //do heavy work on a background thread

    new Thread (new Runnable() {
        @Override
        public void run() {
            Log.d(TAG,"onCreate RUN");
            btScanner.startScan(leScanCallback);
        }
    }).start();
}


@Override
public int onStartCommand(Intent intent,int flags,int startId) {

    Log.d(TAG,"onStartCommand");

    Intent notificationIntent = new Intent(this,MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,notificationIntent,0);

    Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("input")
            .setSmallIcon(R.drawable.ic_one)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1,notification);

    return START_STICKY;
}

private ScanCallback leScanCallback = new ScanCallback() {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onScanResult(int callbackType,ScanResult result) {
        Log.d(TAG,"BLE executed");
        if(result.getDevice().getAddress().equals("EE:7E:DE:9B:65:46") && result.getRSSi() > -80){
            Log.d(TAG,"Tag found");
        }
    }
};

@Override
public void onDestroy() {
    Log.d(TAG,"Destroy");
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)