1

我的应用程序启动了一项检测手机抖动的服务。当服务检测到震动时,它会搜索范围内的 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();
        }
    }
};
4

1 回答 1

1

我找到了答案。我不得不添加一行:

android:foregroundServiceType="location"

在 AndroidManifest.xml 中:

<service
        android:name=".ForegroundService"
        android:exported="true"
        android:enabled="true"
        android:foregroundServiceType="location"
        />
于 2021-10-18T15:40:10.450 回答