Java 从广播接收器(蓝牙)返回值

Java 从广播接收器(蓝牙)返回值,java,android,asynchronous,bluetooth,Java,Android,Asynchronous,Bluetooth,我正试图通过实现自己的android蓝牙库来进行蓝牙聊天。我希望在图形部分和逻辑部分之间有一个清晰的分离(模块化) 为了获得蓝牙设备的列表,我通过编程在我的BluetoothManager类(库)中注册了一个新的BroadcastReceiver 我希望将这些值返回或存储在此类中的数组中,以便可以从我的(外部)活动/片段访问它们 我该怎么做 这是BluetoothManager(库)中的代码: public class BluetoothManager { private Blueto

我正试图通过实现自己的android蓝牙库来进行蓝牙聊天。我希望在图形部分和逻辑部分之间有一个清晰的分离(模块化)

为了获得蓝牙设备的列表,我通过编程在我的BluetoothManager类(库)中注册了一个新的BroadcastReceiver

我希望将这些值返回或存储在此类中的数组中,以便可以从我的(外部)活动/片段访问它们

我该怎么做

这是BluetoothManager(库)中的代码:

public class BluetoothManager {

    private BluetoothAdapter bluetoothAdapter;
    private Context context;

    public BluetoothManager(Context context) {
        this.context = context;
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Log.d("[BluetoothManager]", "Error device does not support Bluetooth");
        }
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add value into an array or return --> TODO 
            }
        }
    };

    public void discovery(){
        // Check if the device is already "discovering". If it is, then cancel discovery.
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        // Start Discovery
        bluetoothAdapter.startDiscovery();
        // Register for broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        context.getApplicationContext().registerReceiver(mReceiver, filter);
    }

    ...

}
public class TabFragment extends ListFragment implements AdapterView.OnItemClickListener {

private BluetoothManager bluetoothManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View fragmentView = inflater.inflate(R.layout.fragment_tab_fragment2, container, false);

    Button button = fragmentView.findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            bluetoothManager = new BluetoothManager(getContext());
            if(bluetoothManager.activeBluetooth()){
                bluetoothManager.discovery();
                // Get Values here --> TODO
            }
        }
    });

    // Add return values into a list
    //final String[] items = ...;
    final ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, items);
    setListAdapter(aa);

    return fragmentView;
    }
}
这是片段中的代码:

public class BluetoothManager {

    private BluetoothAdapter bluetoothAdapter;
    private Context context;

    public BluetoothManager(Context context) {
        this.context = context;
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Log.d("[BluetoothManager]", "Error device does not support Bluetooth");
        }
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add value into an array or return --> TODO 
            }
        }
    };

    public void discovery(){
        // Check if the device is already "discovering". If it is, then cancel discovery.
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        // Start Discovery
        bluetoothAdapter.startDiscovery();
        // Register for broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        context.getApplicationContext().registerReceiver(mReceiver, filter);
    }

    ...

}
public class TabFragment extends ListFragment implements AdapterView.OnItemClickListener {

private BluetoothManager bluetoothManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View fragmentView = inflater.inflate(R.layout.fragment_tab_fragment2, container, false);

    Button button = fragmentView.findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            bluetoothManager = new BluetoothManager(getContext());
            if(bluetoothManager.activeBluetooth()){
                bluetoothManager.discovery();
                // Get Values here --> TODO
            }
        }
    });

    // Add return values into a list
    //final String[] items = ...;
    final ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, items);
    setListAdapter(aa);

    return fragmentView;
    }
}
公共类TabFragment扩展ListFragment实现AdapterView.OnItemClickListener{
私人BluetoothManager BluetoothManager;
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图碎片视图=充气机。充气(R.layout.fragment\u tab\u fragment2,容器,错误);
Button Button=fragmentView.findViewById(R.id.button2);
setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
bluetoothManager=新的bluetoothManager(getContext());
if(bluetoothManager.activeBluetooth()){
bluetoothManager.discovery();
//在此处获取值-->待办事项
}
}
});
//将返回值添加到列表中
//最终字符串[]项=。。。;
最终ArrayAdapter aa=新的ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1,items);
setListAdapter(aa);
返回碎片视图;
}
}

您不能将广播接收器的值作为其事件驱动返回。您可以在onReceive()中将这些值全局保存到集合中(在同一个类中或在单例包装类中),然后在整个应用程序中使用它


要发送值更新回调,另一个本地广播接收器将很有帮助

不能将值从广播接收器返回为其事件驱动。您可以在onReceive()中将这些值全局保存到集合中(在同一个类中或在单例包装类中),然后在整个应用程序中使用它


要发送值更新回调,另一个本地广播接收器将很有帮助

发现可用蓝牙设备的列表是异步的。在接收广播时,BluetoothManager类可以将更新后的设备列表保存在一个列表成员变量中,并公开一个公共getter方法来从活动或片段中检索它。此外,考虑将侦听器暴露到您的活动中,以提供更新的列表,因为设备可以动态地添加或删除。在任何时间点,UI在收到更新的设备列表时都应该刷新自己

public void onClick(视图v){
bluetoothManager=新的bluetoothManager(getContext());…}

这是个坏主意。理想情况下,您必须在创建活动或片段时实例化BluetoothManager类,以便在用户单击按钮之前找到设备列表

我的建议是:

  • 在onCreate of Activity中实例化BluetoothManager,将构造函数更改为接受回调对象,以便在设备列表更改时通知
  • 收听BluetoothManager中的广播,以确定设备的添加或删除。更新本地列表,每当更新发生时,通知UI的回调
  • 在活动/片段中实现回调,并在收到BluetoothManager类的更新时更新UI
  • 当用户单击按钮时,调用BluetoothManager获取更新的设备列表并更新您的UI
  • 从活动的onDestroy中注销BluetoothManager中注册的广播(非常重要。否则将导致内存泄漏
  • 或者,如果您希望与多个活动共享Bluetooth manager实例,请将Bluetooth manager设置为单例,并向应用程序上下文注册BroadcastReceiver。请确保在您的所有活动都已销毁且不再需要接收器时注销广播接收器

    更新: 回调可以是由活动或片段实现的接口。示例代码如下:

            public interface BluetoothDevicesAvailable {
        void onBluetoothDeviceListChanged(List<BluetoothDevice> deviceList);
        }
    
        public class SomeActivity implements BluetoothDevicesAvailable {
        //... Some code
    
        @Override
        public void onBluetoothDeviceListChanged(List<BluetoothDevice> deviceList) {
        //Add your logic here to update UI
        }
    }
    
    公共接口蓝牙设备可用{
    更改Bluetooth设备列表时无效(列出设备列表);
    }
    公共类SomeActivity实现BluetoothDevicesAvailable{
    //…一些代码
    @凌驾
    Bluetooth设备列表上的公共无效已更改(列出设备列表){
    //在此处添加逻辑以更新UI
    }
    }
    
    发现可用蓝牙设备的列表是异步的。在接收广播时,BluetoothManager类可以将更新后的设备列表保存在一个列表成员变量中,并公开一个公共getter方法来从活动或片段中检索它。此外,考虑将侦听器暴露到您的活动中,以提供更新的列表,因为设备可以动态地添加或删除。在任何时间点,UI在收到更新的设备列表时都应该刷新自己

    public void onClick(视图v){
    bluetoothManager=新的bluetoothManager(getContext());…}

    这是个坏主意。理想情况下,您必须在创建活动或片段时实例化BluetoothManager类,以便在用户单击按钮之前找到设备列表

    我的建议是:

  • 在onCreate of Activity中实例化BluetoothManager,将构造函数更改为接受回调对象,以便在设备列表更改时通知
  • 收听BluetoothManager中的广播,以确定设备的添加或删除。更新您的本地列表,并在