【发布时间】:2026-02-11 14:40:01
【问题描述】:
我有一种方法,我使用意图过滤器注册广播接收器以发现蓝牙设备。
// 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,对我来说太高了。有什么建议吗?
【问题讨论】:
标签: java android broadcastreceiver intentfilter