簡體   English   中英

從BroadcastReceiver返回值(藍牙)

[英]Return values from BroadcastReceiver (Bluetooth)

我正在嘗試通過實現自己的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;
    }
}

您不能從廣播接收器返回值,因為它是事件驅動的。 您可以在onReceive()中進行操作,可以將這些值全局保存到Collection中(在同一類中或在Singleton包裝器類中),然后在整個應用程序中使用它。

要發送值的回調更新,另一個本地廣播接收器將很有幫助。

發現可用藍牙設備列表是異步的。 收到廣播后,BluetoothManager類可以將更新后的設備列表保存在列表成員變量中,並公開一個公共getter方法以從Activity或fragment中檢索它。 另外,由於設備可以不斷地動態添加或刪除,因此請考慮將監聽器暴露給您的活動以提供更新的列表。 在任何時間點,UI都應在接收到更新的設備列表后刷新自身。

public void onClick(View v) { bluetoothManager = new BluetoothManager(getContext()); ...}

是個壞主意。 理想情況下,您必須在活動或片段的onCreate上實例化BluetoothManager類,以便在用戶單擊按鈕之前提前發現設備列表。

我的建議是:

  1. 在Activity的onCreate上實例化BluetoothManager,更改構造函數以接受回調對象,以在設備列表更改時通知。
  2. 在BluetoothManager中收聽廣播,以識別設備的添加或刪除。 更新您的本地列表,每當發生更新時,通知UI的回調
  3. 每當您從BluetoothManager類收到更新時,在活動/片段中實現回調並更新UI。
  4. 當用戶單擊按鈕時,調用BluetoothManager以獲取設備的更新列表並更新您的UI。
  5. 從活動的onDestroy中注銷在BluetoothManager中注冊的廣播( 非常重要。否則,這會導致內存泄漏

或者,如果您想與多個活動共享Bluetooth管理器實例,請將BluetoothManager設置為單例並向應用程序上下文注冊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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM