我有一種方法,使用意向過濾器註冊廣播接收器來發現藍牙設備。如何等待廣播接收器完成
// global variable
String xpto = "empty";
這裏是無效的方法:
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());
我的問題是:由於該方法中的代碼是順序執行的,由我嘗試(序列中的那個方法)使用一些時間我在Broadcast Receiver中分配的全局變量,它們仍然爲null或爲空。
我已經在一些「解決方案」中將我的「主代碼」從位置移動到廣播接收器,或者在BR完成時將一些其他全局變量分配爲1(並且在主代碼中有一段時間x =!1等待),但這不是很好的編程,我相信有一個正確的方法來做到這一點。
我發現了PendingResult,但API Level 11對我來說太高了。有什麼建議麼?
我把這個代碼http://pastebin.com/mXG6iyW6的類App放在另一個文件中,並且在清單中添加了這個,但是我仍然收到了空值。我不瞭解什麼? – Tiago 2012-01-05 15:12:42
我編輯了我的代碼,以便您瞭解我的問題。 – Tiago 2012-01-05 16:49:16
我來看看。空僅僅是我們必須處理的事情之一。 :) – 2012-01-05 21:57:15