[英]AlarmManager does not work in foreground service, when app was killed
[英]BluetoothAdapter StartDiscovery does not work in Foreground Service
我的應用程序啟動了一項檢測手機抖動的服務。 當服務檢測到震動時,它會搜索范圍內的 BT 設備,如果找到合適的設備,它會連接到該設備並向其發送數據。
為了檢查系統是否正在終止服務,我在檢測到震動時打開震動。
當 Activity 在主屏幕上時,一切正常。 但是,當我關閉 Activity 時,服務檢測到震動,但設備搜索未啟動(BroadcastReceiver onReceive 未收到任何 Intent)。
從后台服務搜索藍牙設備有什么限制嗎? 如何解決這個問題?
應用權限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
在 ForegroundService.java 中啟動發現代碼
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
cnt.registerReceiver(receiver, filter);
btAdapter.startDiscovery();
廣播接收器
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent i)
{
String action = i.getAction();
//Log.d("BluetoothFinder", "receiver action: " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = i.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
String name = "<brak nazwy urządzenia>";
if (device.getName() != null) name = device.getName();
BTDevice d = new BTDevice(device.getAddress(), name, true,
(device.getBondState() != BluetoothDevice.BOND_BONDED) ? BTDevice.UNBONDED : BTDevice.BONDED, rssi);
if (addDevIfDoesntExists(d))
{
newBTDevice = d;
Log.d("BluetoothFinder", "Znaleziono nowe urządzenie: " + d.MAC + " rssi: " + rssi);
try { methodParamOnFound.call(); } catch (Exception e) {}
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
Log.d("BluetoothFinder", "ACTION_DISCOVERY_FINISHED");
try { methodParamOnEnd.call(); } catch (Exception e) { }
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))
{
Log.d("BluetoothFinder", "ACTION_DISCOVERY_FINISHED");
btDevices.clear();
}
}
};
我找到了答案。 我不得不添加行:
android:foregroundServiceType="location"
在 AndroidManifest.xml 中:
<service
android:name=".ForegroundService"
android:exported="true"
android:enabled="true"
android:foregroundServiceType="location"
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.