我有一个使用3个前台服务通过BluetoothLeScanner扫描和处理信标的应用程序。其中只有一个具有扫描它们的代码,其他两个服务则处理扫描的信标并进行一些api调用。 几个小时后,前台服务停止工作,并且通知消失。
通过ScanCallback onScanResult进行扫描。每5分钟重新启动一次扫描,以避免Android停止扫描。
我使用START_STICKY运行前台服务。我已经制作了一个广播接收器,该广播接收器在调用onDestroy()方法时重新启动服务。
@Override
public void onCreate() {
Log.i("EntryDetectionService", "Starting Service");
super.onCreate();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "Beacon Reader";
String CHANNEL_NAME = "Scanning Beacons";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setCategory(Notification.CATEGORY_SERVICE).setPriority(PRIORITY_HIGH)
.setSmallIcon(R.drawable.ic_launcher)
.build();
startForeground(101, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.getBluetoothScanner();
mainLoopHandler.post(scan);
return START_STICKY;
}
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
List<ScanFilter> filters = new ArrayList<>();
ScanFilter filter = new ScanFilter.Builder()
.setManufacturerData(76, new byte[] {})
.build();
filters.add(filter);
if (bluetoothAdapter.isEnabled())
bleScanner.startScan(filters, settings, scanCallback);
谢谢!
答案 0 :(得分:0)
使APP保持活动状态 当api> 21时,您可以使用 JobScheduler
某些设备可能会使应用保持活动状态。
jobScheduler android example code
onStartJob 时检查服务是否仍然存在
public boolean isServiceRunning(Context context, String serviceName) {
boolean isRunning = false;
ActivityManager am = (ActivityManager) this
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo info : lists) {
System.out.println(info.processName);
if (info.processName.equals(serviceName)) {
isRunning = true;
}
}
return isRunning;
}