Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing WiFi-direct from switching off when not used

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();

        }
like image 917
Devester Avatar asked Apr 13 '15 09:04

Devester


Video Answer


1 Answers

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?

like image 114
Tomasz Gawel Avatar answered Sep 22 '22 08:09

Tomasz Gawel