如何解决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 举报,一经查实,本站将立刻删除。