在我的应用程序中,我有一个Service
,其中包含一个Thread
,可以启动和停止BLE广告:
public class BeaconSearchService extends Service {
private void startAdvertisingThread() {
(advertisingThread = new Thread("Advertising Thread") {
@Override
public void run() {
//Ensure that advertising is off
try {
BeaconSearchService.this.bluetoothLeAdvertiser.stopAdvertising(BeaconSearchService.this.advertiseCallback);
} catch (Exception e) {
}
while(!isInterrputed()) {
AdvertiseSettings advertiseSettings = new AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
.setConnectable(true)
.build();
BeaconSearchService.this.advertiseData.getServiceUuids().clear();
BeaconSearchService.this.advertiseData.getServiceUuids().add(BeaconSearchService.this.getUuid());
long uptime = 5000;
long downTime = 7000;
//START ADVERTISING
try {
BeaconSearchService.this.bluetoothLeAdvertiser.startAdvertising(advertiseSettings, BeaconSearchService.this.advertiseData, BeaconSearchService.this.advertiseCallback);
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
//SLEEP FOR 5 SEC
try {
sleep(upTime);
} catch (InterruptedException e) {
interrupt();
break;
}
//AFTER WAKE FROM SLEEP, STOP ADVERTISING
try {
BeaconSearchService.this.bluetoothLeAdvertiser.stopAdvertising(BeaconSearchService.this.advertiseCallback);
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
//SLEEP FOR 7 SEC
try {
sleep(downTime);
} catch (InterruptedException e) {
interrupt();
break;
}
//RESTART THE CIRCLE IF NOT INTERRUPTED
}
//Ensure stop advertising while exiting
try {
BeaconSearchService.this.bluetoothLeAdvertiser.stopAdvertising(BeaconSearchService.this.advertiseCallback);
} catch (Exception e) {
}
}).start();
}
@Override
public void onDestroy() {
try {
advertisingThread.interrupt();
} catch(Exception e) {
}
}
}
问题是当广告开启且Service
和Thread
关闭而没有调用onDestroy()
方法(例如应用崩溃,应用程序进程被本地Android ROM自定义行为杀死或者在使用Android Studio进行开发时,从Playstore等新版本下载后重新启动应用程序,Android系统会保持BLE广告开启。因此,当我重新打开应用程序并嗅探BLE数据包时,我会看到我的应用程序的两个或更多广告“会话”。当我重新启动手机并且“孤儿”广告会话消失时,问题就解决了。
有没有办法在不强迫用户重启手机的情况下杀死所有“僵尸”广告会话?