几天前,我能够成功使Android使用PendingIntents
扫描BLE设备。今天,我在获取PendingIntent来接收任何回调数据方面遇到了麻烦,而且我正在努力寻找原因。
我正在使用Android文档中定义的以下功能:
来自https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner:
startScan(List<ScanFilter> filters, ScanSettings settings, PendingIntent callbackIntent)
我已在清单中添加了以下权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
我也已经声明我正在使用此接收器:
<receiver android:name="com.myapp.PendingIntentScanReceiver" >
<intent-filter>
<action android:name="BluetoothDevice.ACTION_FOUND" />
<action android:name="BluetoothDevice.EXTRA_UUID" />
<action android:name="BluetoothDevice.EXTRA_RSSI" />
</intent-filter>
</receiver>
以及此PendingIntentScanReceiver
的实现:
public class PendingIntentScanReceiver extends BroadcastReceiver {
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "Hello there.");
}
}
我正在使用三星Galaxy S8并阅读here,我不应该为扫描过滤器传递null
(因为我猜这在三星设备上无法正常工作?)。
我也曾尝试将startScan
调用从后台服务移至MainApplication,再移至MainActivity,但这些似乎都无法改善结果。
顺便说一下,我的startScan
代码如下所示:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
List<ScanFilter> listOfFiters = new ArrayList<>();
ScanFilter.Builder builder = new ScanFilter.Builder();
ScanFilter filter = builder.build();
listOfFiters.add(filter);
BluetoothManager bluetoothManager =
(BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
Intent intent = new Intent(getApplicationContext(), PendingIntentScanReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 42, intent, 0);
int scanRes = bluetoothAdapter.getBluetoothLeScanner().startScan(listOfFiters, settings, pendingIntent);
// (scanRes is always 0 during my tests)
}
我的问题是:为什么“你好”。从未印过?有什么我忘记的东西吗?
答案 0 :(得分:0)
这是Oreo, BLE scanner startScan with PendingIntent not working on Samsung device
的副本请检查以下答案:https://stackoverflow.com/a/54198717/2115352
TL; DR:
startScan
。<receiver>
的{{1}} <intent-filter>
<receiver android:name="com.myapp.PendingIntentScanReceiver" >
<intent-filter>
<action android:name="com.myapp.ACTION_FOUND" />
</intent-filter>
</receiver>
返回 null 。答案 1 :(得分:-1)
如官方文档所述
除少数例外,应用程序无法使用其清单来注册隐式广播。他们仍然可以在运行时注册这些广播,并且可以使用清单注册专门针对其应用的显式广播。
我认为这与后台任务的工作方式密切相关,而不是ble
问题。请仔细查看android Oreo
here的api更改。我认为您应该实施前台服务来完成这些操作。