gpt4 book ai didi

java - 当应用程序关闭时 AltBeacon 继续扫描

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:54 26 4
gpt4 key购买 nike

我正在使用AltBeacon信标扫描库来扫描信标。我在服务中启动信标扫描仪,该服务在启动时或蓝牙状态更改时由广播接收器调用。当我打开应用程序并再次退出时,BeaconHandler 会被终止并重新启动,因为信标服务再次调用广播接收器。

问题是我不希望在退出应用程序时重置信标扫描仪,因为我将所有扫描的信标保存在 ArrayList 中,并且需要跟踪用户在建筑物中的移动。因此,当我退出应用程序时,我的 Arraylist 被清除,并且我无法跟踪用户的移动。

我的后台服务:

public class BeaconService extends Service {
private static final String TAG = "BeaconService";

private BeaconHandler beaconHandler;

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

@Override
public void onCreate() {
super.onCreate();

Log.e(TAG, "onCreate()");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand()");

beaconHandler = BeaconHandler.getInstance(getApplicationContext(),
BeaconHandler1.getInstance(getApplicationContext()),
BeaconHandler2.getInstance(getApplicationContext()));

return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();

Log.e(TAG, "onDestroy()");

beaconHandler.stopListening();

sendBroadcast(new Intent(this, BluetoothReceiver.class));
}
}

我的广播接收器:

public class BluetoothReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.e("BluetoothReceiver", "onReceive()");

if (BeaconManager.getInstanceForApplication(context).checkAvailability()) {
context.startService(new Intent(context, BeaconService.class));
} else {
context.stopService(new Intent(context, BeaconService.class));
}
}
}

正如您所看到的,信标处理程序是一个单例类,因此一次只有一个实例在运行。有没有办法防止信标扫描仪重置并在应用程序关闭时清除我的ArrayList

最佳答案

如果内存不足,您无法阻止应用程序被用户或操作系统杀死。

解决方案是将应用程序状态保存在非 volatile 存储中,然后在服务启动时将其读回。 SharedPreferences如果您的数据很简单,这是一个很好的存储机制。

请记住,您无法控制应用程序何时被终止,或者在应用程序发生时依赖回调,因此您需要定期保存数据。

关于java - 当应用程序关闭时 AltBeacon 继续扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34442514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com