我有一个应用程序,它使用 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);
谢谢!!
最佳答案
保持APP存活 当 api>21 时,可以使用 JobScheduler
某些设备可能会使应用程序保持 Activity 状态。
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;
}
关于java - 几个小时后前台服务停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57587966/