问题描述
我正在尝试复制下面的Java代码,该代码应该在android设备上扫描蓝牙设备,但是我正在尝试使用pyjnius java到python包装器在python中编写代码。
关于如何执行此操作的文档很少,因此我无法弄清楚如何使其工作,查看Java代码,似乎onReceive
类中的功能broadcastReceiver
被覆盖,但不是确定如何在python中做到这一点。当前,代码只是失败而没有任何调用回溯,所以我什至无法调试它。
感谢您的帮助
Java蓝牙代码
mBluetoothAdapter.startdiscovery();
mReceiver = new broadcastReceiver() {
public void onReceive(Context context,Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
python代码
from android.broadcast import broadcastReceiver
from jnius import autoclass
from android.permissions import request_permissions,Permission
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
broadcastReceiver = autoclass('android.content.broadcastReceiver')
IntentFilter = autoclass('android.content.IntentFilter')
Intent = autoclass('android.content.Intent')
request_android_permissions()
mBLuetoothAdapter = BluetoothAdapter.getDefaultDevice()
mBLuetoothAdapter.startdiscovery()
mReceiver = broadcastReceiver(self.on_broadcast,actions = ['ACTION.FOUND'])
mReceiver.start()
def request_android_permissions():
def callback(permissions,results):
if all([res for res in results]):
print("callback. All permissions granted")
else:
print("callback. Some permissions refused")
request_permissions([Permission.ACCESS_COARSE_LOCATION,Permission.ACCESS_FINE_LOCATION])
def onReceive(context,intent):
action = intent.getAction()
if BluetoothDevice.ACTION_FOUND.equals(action):
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
Devices.append(device.getName() + " " + device.getAddress())
filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
broadcastReceiver.registerReceiver(mReceiver,filter)
解决方法
我使用BroadcastReceiver进行WiFi扫描,它可以正常工作,您应该可以将此示例改编为蓝牙。
https://github.com/kivy/python-for-android/issues/2308
这是在“问题”中,因为BroadcastReceiver中存在崩溃错误,该崩溃错误是在第二次启动时发生的,例如从on_resume()开始。该修复程序将在第二篇文章中进行介绍,并且需要克隆p4a的本地副本,按照说明进行编辑,然后在.spec中使用p4a.source_dir
指向它。