简体   繁体   English

如何等待广播接收器完成

[英]How to wait for Broadcast Receiver to finish

I have a method where I register broadcast receivers using intent filters to discover bluetooth devices. 我有一种方法,我使用意图过滤器注册广播接收器来发现蓝牙设备。

// global variable
 String xpto = "empty";

Here is the void method: 这是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());

My problem is: because the code in that method is executed sequentially, by the time I try to use (in that method in the sequence) some global variables I allocate in Broadcast Receiver, they are still null or empty. 我的问题是:因为该方法中的代码是按顺序执行的,当我尝试使用(在序列中的该方法中)我在广播接收器中分配的一些全局变量时,它们仍为或空。

I've though in some "solutions" like moving my "main code" from place to broadcast receiver, or having some other global variable alocated to 1 when BR is finished (and a while x =! 1 in main code to wait) but this is not good programming, I'm sure there is a correct way to do that. 我有一些“解决方案”,比如将我的“主代码”从地方移动到广播接收器,或者当BR完成时将一些其他全局变量分配到1(并且在主代码中等待x =!1)但是这不是很好的编程,我确信有一个正确的方法来做到这一点。

I've found PendingResult but is API Level 11, too high for me. 我发现PendingResult但是API等级11,对我来说太高了。 Any suggestions? 有什么建议么?

If it is used by multiple components and is truly "global" to your application, you may extend the Application object and use it there. 如果它被多个组件使用并且对您的应用程序真正“全局”,您可以扩展Application对象并在那里使用它。 This means the it will be allocated before either of your components starts and it is accessible to all of your components. 这意味着它将您的任一组件启动之前分配 并且所有组件都可以访问它。 It is also "safe" and recommended by many as "global" variables are outside of the Lifecycle as is the Application object. 它也是“安全的”并且被许多人推荐为“全局”变量在生命周期之外,与Application对象一样。 As long as both Components are not either reading and writing at the SAME instant, you should be fine. 只要两个组件都不是在同一时刻读写,你应该没问题。 If you foresee an issue there, you can make the code thread-safe by synchronizing it, as well. 如果你预见到那里的问题,你也可以通过同步使代码线程安全。

A word of warning on extending the Application. 关于扩展申请的警告。 This should not be used for everything that requires multiple objects to access it. 这不应该用于需要多个对象访问它的所有内容。 This should only be used for data that needs to remain outside of the Lifecycle out of necessity. 这仅应用于需要在生命周期之外保留的数据。

Please let me know if you need clarification on how to extend an Application and access the new data. 如果您需要澄清如何扩展Application并访问新数据,请与我们联系。

Hope this helps, FuzzicalLogic 希望这会有所帮助,FuzzicalLogic

Maybe you can use wait() and notify().. Take care to do it synchronyzed: 也许你可以使用wait()和notify()..注意同步:

NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

synchronized (nm) {
            try {
                // Esperar a que finalice la descarga
                nm.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

Refer to Threading in Java: How to lock an object? 请参阅Java中的线程:如何锁定对象? and also how to fire notification from BroadcastReceiver? 以及如何从BroadcastReceiver发出通知?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM