gpt4 book ai didi

java - 如何等待广播接收器完成

转载 作者:太空狗 更新时间:2023-10-29 13:37:55 25 4
gpt4 key购买 nike

我有一种方法可以使用 Intent 过滤器注册广播接收器以发现蓝牙设备。

// global variable
String xpto = "empty";

这里是 void 方法:

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {

App appState = ((App)getApplicationContext());
appState.setTeste("OLAAAAA");

String action = intent.getAction();

elementos = new Vector<String>();

String delimiter = "_";
String[] temp = null;

xpto = "OLA";

// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


// SO VAI VERIFICAR DO QUE ESTAO PRESENTES (DISCOVERABLE) OS QUE ESTAO PAIRED
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.v("TAG","PAIRED AND PRESENT="+device.getName());
temp = device.getName().split(delimiter);
}

int aux = 0;

if(temp != null)
{
for(int i =0; i < temp.length ; i++)
{
if(temp[aux].equals("SapoFit"))
{
elementos.add(temp[aux]+"_"+temp[aux+1]);
Log.v("TAG","Seleccionado="+temp[aux]+"_"+temp[aux+1]);
}
aux++;
}

elSelecionado = temp[0]+"_"+temp[0+1];

}

}

}
};

this.registerReceiver(mReceiver, filter);

Log.v("TAG","HERE COMES empty="+xpto.toString());

我的问题是:因为该方法中的代码是按顺序执行的,所以当我尝试使用(在该序列中的该方法中)我在广播接收器中分配的一些全局变量时,它们仍然是 null 或空。

虽然在一些“解决方案”中,比如将我的“主代码”从一个地方移动到广播接收器,或者在 B.R 完成时将一些其他全局变量分配给 1(并且主代码中的 x =!1 到等等)但这不是好的编程,我相信有一个正确的方法来做到这一点。

我找到了 PendingResult 但它是 API 级别 11,对我来说太高了。有什么建议吗?

最佳答案

如果它被多个组件使用并且对您的应用程序来说是真正“全局的”,您可以扩展 Application 对象并在那里使用它。这意味着它将在之前您的任一组件启动时分配并且您的所有组件都可以访问它。它也是“安全的”并被许多人推荐,因为“全局”变量和应用程序对象一样在生命周期之外。只要两个组件不是同时读取和写入,就应该没问题。如果您预见到那里会出现问题,您也可以通过同步代码使代码线程安全。

关于扩展应用程序的警告。这不应该用于需要多个对象访问它的所有内容。这应该仅用于出于必要而需要保留在生命周期之外的数据。

如果您需要说明如何扩展 Application 和访问新数据,请告诉我。

希望对您有所帮助,模糊逻辑

关于java - 如何等待广播接收器完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8742503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com