使用pyjnius java包装器的Python蓝牙设备扫描

2024-06-26 00:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图复制下面的java代码,该代码应该用于在android设备上扫描蓝牙设备,但我试图使用pyjnius java to 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)


Tags: 代码frompermissionsdeviceactionandroidfoundintent
1条回答
网友
1楼 · 发布于 2024-06-26 00:22:33

我使用BroadcastReceiver进行WiFi扫描,它可以工作,您应该能够将此示例应用于蓝牙

https://github.com/kivy/python-for-android/issues/2308

这是“问题”中的问题,因为BroadcastReceiver中有一个崩溃错误,它发生在第二次启动时,例如从on_resume()开始。修复程序在第二篇文章中描述,需要克隆p4a的本地副本,按照描述进行编辑,并在.spec中用p4a.source\u dir指向它

相关问题 更多 >