![](/img/trans.png)
[英]How to make BLE scan and MQTT publish work in background Android Studio Java
[英]BLE Scan not working in Background with Scanfilters in android pie?
我正在使用 blescan 和 scanfilters 來檢測信標,它在前景和背景中工作得非常好,直到 oreo 版本,但是當涉及到 android pie 時,它無法在后台發送待處理的廣播。
ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
final List<ScanFilter> scanFilters = new ArrayList<>();
scanFilters.add(getScanFilter());
BluetoothAdapter bluetoothAdapter;
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
Intent intent = new Intent(this.getApplicationContext(), MyBroadcastReceiver.class);
intent.putExtra("o-scan", true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
bluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, settings, pendingIntent);
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int bleCallbackType = intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, -1);
if (bleCallbackType != -1) {
Log.d(TAG, "Passive background scan callback type: "+bleCallbackType);
ArrayList<ScanResult> scanResults = intent.getParcelableArrayListExtra(
BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT);
// Do something with your ScanResult list here.
// These contain the data of your matching BLE advertising packets
}
}
}
Android 9 引入了多項行為更改,例如限制后台應用程序對設備傳感器和 Wi-Fi 掃描的訪問。
無論目標 SDK 版本如何,這些更改都會影響在 Android 9 上運行的所有應用。
使用連續報告模式的傳感器,例如加速度計和陀螺儀,不會接收事件。
Android 9 在后台限制訪問傳感器:
Android 9 限制了后台應用訪問用戶輸入和傳感器數據的能力。 如果您的應用在運行 Android 9 的設備上在后台運行,系統會對您的應用應用以下限制:
使用連續報告模式的傳感器(例如加速度計和陀螺儀)不會接收事件。
使用on-change或one-shot報告模式的傳感器不接收事件。
解決方案:如果您的應用需要在運行 Android 9 的設備上檢測傳感器事件而應用在后台,請使用前台服務。
我使用 Oreo (API 26) 和上面的代碼(稍作修改)來檢測信標的示例測試 Android 應用程序。 我正在使用 Pixel 3 XL(帶 Pie)。 我認為關於此的困難部分是確定當設備僅使用電池運行時(與 Android-studio 和 Logcat (USB) 斷開連接),MyBroadcastReceiver 中的 onRecieve() 中的代碼是否在檢測到信標時實際運行)。
使用 Volley (com.android.volley) 向本地 http 服務器提交 HTTP 請求,我能夠證明它的工作方式與文檔一致 - 即。 當檢測到信標時,我能夠接收到 http 請求。 但是,Volley 僅在 Android 處於喚醒狀態或定期喚醒並連接到網絡時發送這些請求 - 在我的簡單測試中大約每 15 分鍾一次(加上一些變化),但我確實在我的HTTP 服務器,只是在延遲達 15 分鍾。 我什至能夠從正在運行的應用程序列表中刪除該應用程序(您知道;向上滑動以刪除該應用程序),並且仍然看到 MyBroadcastReceiver 中的 onRecieve() 正在接收 BLE ScanResults。
你怎么知道 MyBroadcastReceiver 中的 onRecieve() 被殺死了? 我很想知道你是怎么知道的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.