【问题标题】:Android: WiFi-Direct communication when screen is offAndroid:屏幕关闭时的 WiFi-Direct 通信
【发布时间】:2016-10-04 15:27:16
【问题描述】:

我正在使用 WiFi-Direct 在 Android 上尝试 P2P 通信。我有一项服务,可以搜索其他手机并在它们之前配对时自动连接到它们。无论屏幕是开还是关,我都喜欢让它工作。

Android 提供了在设备屏幕关闭时保持 WiFi 活动的选项。但它看起来并不影响 WiFi-Direct。在关闭设备屏幕并等待一分钟后,WifiP2pManager 似乎停止发现新的对等点。

有人知道如何解决这种行为吗?

【问题讨论】:

    标签: android wifi android-wifi wifi-direct wifip2p


    【解决方案1】:

    所以这里发生的情况是,您在屏幕关闭 50 秒后调用 startDiscoveryProcess(),而 startDiscoveryProcess() 每 50 秒调用一次。如何停止该过程?您收听Intent.ACTION_SCREEN_ON,如果屏幕开启,我们不会发送广播以再次开始发现。

    boolean screenOn = true;
    
    BroadcastReceiver screenReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF) || intent.getAction().equals("MY_ACTION_WHEN_SCREEN_IS_OFF")) {
                screenOn = false;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // start discovery process again
                        startDiscoveryProcess();
                    }
                }, 50000);
            }  else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                screenOn = true;
            }
        }
    };
    

    在你的服务的onCreate(),注册接收者:

    IntentFilter filters = new IntentFilter();
    filters.addAction(Intent.ACTION_SCREEN_OFF);
    filters.addAction(Intent.ACTION_SCREEN_ON);
    filters.addAction("MY_ACTION_WHEN_SCREEN_IS_OFF");
    registerReceiver(screenReceiver, filters);
    

    那么只要确保有我们上面调用的方法:

    void startDiscoveryProcess() {
        //start discovery process
        // do something...
    
        // then send the broadcast yourself to do this every 50 seconds because discovery stops at 60 seconds
        if(!screenOn) {
            Intent intent = new Intent("MY_ACTION_WHEN_SCREEN_IS_OFF");
            sendBroadcast(intent);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-26
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      相关资源
      最近更新 更多