5

I am targeting API 17 and using the code below to enable the WiFi-direct (P2P). Everything works fine (finding and connecting to peers), however when not used WiFi-direct keeps switching off from time to time (looks like it depends on the android phone - mine is around 3-5 min) which will also switch the WiFi off making me lose Internet connection.

I have a receiver that detects when the P2P's state changes to switch it back on, but it would be great to keep the P2P always on even when it is not connected to any peer.

Would it be possible to keep pinging the android phone itself in order to do that? Any other suggestion?

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {

        // UI update to indicate wifi p2p status.
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
            // Wifi Direct mode is enabled
            activity.setIsWifiP2pEnabled(true);
        } else {
            activity.setIsWifiP2pEnabled(false);
            activity.resetData();

        }
Devester
  • 1,183
  • 4
  • 14
  • 41
  • 1
    Do that not consume much of your device battery,rather pinging for some time intervals? – Tharif Apr 13 '15 at 09:51
  • Have you really gone through your code, that its not the one causing the switch off ? generally the API should not do that automatically. – Dr.Jukka Apr 15 '15 at 07:06

1 Answers1

5

You should acquire WifiLock. Or did you?

From javadoc entry for WakeLock:

Normally the Wi-Fi radio may turn off when the user has not used the device in a while. Acquiring a WifiLock will keep the radio on until the lock is released.

See more on WifiLock: http://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock.html

Read also answer to this question: Is using WakeLock overkill while using WifiLock on Android?

Community
  • 1
  • 1
Tomasz Gawel
  • 8,379
  • 4
  • 36
  • 61