[Wifi Direct Demo]间隔多次运行相同的代码[Android]

时间:2018-02-07 05:47:43

标签: android android-handler

我关注https://android.googlesource.com/platform/development/+/master/samples/WiFiDirectDemo

由于我自己的要求,我只想多次运行以下代码。 enter image description here

当我们点击搜索按钮(以红色显示)时,该应用程序开始搜索可用的wifi对等体,如下图所示

enter image description here

我只想每2秒自动执行一次这个过程,无论是否找到了同伴。

在此活动的代码中:

                case R.id.atn_direct_discover:
            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return true;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
            return true;

这是代码。

我试过的一件事是在一段时间(真实)循环中进行翻转,但我总是让应用程序崩溃。 然后我使用了一个停止按钮和一个标志。这个按钮将标志设置为false但它仍然无效。

我尝试了这个解决方案:How to automatically Click a Button in Android after a 5 second delay 它不会使应用程序崩溃,但只有当我手动点击它时按钮才会生效。

任何建议请??

2 个答案:

答案 0 :(得分:0)

我从您的问题中了解到,您希望任务在没有任何用户干预的情况下运行,以检测新的对等方并相应地更新您的UI。

当您的应用程序位于前台时,每5秒运行一次处理程序以启动绑定服务以搜索任何新对等方,如果已找到任何新内容,该服务会将该信息传回活动。当您在Activity上收到消息时,请停止该服务并取消绑定。

请在此处查看有关约束服务的详细信息 - https://developer.android.com/guide/components/bound-services.html

答案 1 :(得分:0)

您可以使用Timer课程&安排它每5秒运行一次。这个想法是计时器任务不模拟按下按钮,但它应该与按下按钮完全相同。

假设您的Activity班级名为MyActivity。将其放在onCreate() MyActivity课程的Timer myTimer = new Timer(); // schedule to run every 5000 milli seconds myTimer.schedule(new TimerTask() { @Override public void run() { MyActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // any code that update UI goes here // Eg: displaying progress indicator, show "finding Peers" text .... } }); // the rest of "discover" logic goes here } }, 0, 5000); 中。

{{1}}