Example usage for android.net.wifi WifiManager createWifiLock

List of usage examples for android.net.wifi WifiManager createWifiLock

Introduction

In this page you can find the example usage for android.net.wifi WifiManager createWifiLock.

Prototype

public WifiLock createWifiLock(int lockType, String tag) 

Source Link

Document

Creates a new WifiLock.

Usage

From source file:github.popeen.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*  w ww.  ja  v a2s .  c  om*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            /*try {
               Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
               i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
               i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
               sendBroadcast(i);
            } catch(Throwable e) {
               // Froyo or lower
            }*/

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;//w ww. ja va2 s.c o m
    int lcv2 = 0;
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wc = new WifiConfiguration();
    DoCommand tmpdc = new DoCommand(getApplication());

    String ssid = tmpdc.GetIniData("Network Settings", "SSID", sIniFile);
    String auth = tmpdc.GetIniData("Network Settings", "AUTH", sIniFile);
    String encr = tmpdc.GetIniData("Network Settings", "ENCR", sIniFile);
    String key = tmpdc.GetIniData("Network Settings", "KEY", sIniFile);
    String eap = tmpdc.GetIniData("Network Settings", "EAP", sIniFile);
    String adhoc = tmpdc.GetIniData("Network Settings", "ADHOC", sIniFile);

    Toast.makeText(getApplication().getApplicationContext(), "Starting and configuring network",
            Toast.LENGTH_LONG).show();
    /*
            ContentResolver cr = getContentResolver();
            int nRet;
            try {
    nRet = Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP);
    String foo2 = "" + nRet;
            } catch (SettingNotFoundException e1) {
    e1.printStackTrace();
            }
    */
    /*
            wc.SSID = "\"Mozilla-Build\"";
            wc.preSharedKey  = "\"MozillaBuildQA500\"";
            wc.hiddenSSID = true;
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    */
    wc.SSID = "\"" + ssid + "\"";
    //        wc.SSID = "\"Mozilla-G\"";
    //        wc.SSID = "\"Mozilla\"";

    if (auth.contentEquals("wpa2")) {
        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wc.preSharedKey = null;
    }

    if (encr.contentEquals("aes")) {
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    }

    if (eap.contentEquals("peap")) {
        wc.eap.setValue("PEAP");
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
    }

    wc.status = WifiConfiguration.Status.ENABLED;

    if (!wifi.isWifiEnabled())
        wifi.setWifiEnabled(true);

    while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
        Thread.yield();
        if (++lcv > 10000)
            return (bRet);
    }

    wl = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL, "SUTAgent");
    if (wl != null)
        wl.acquire();

    WifiConfiguration foo = null;
    int nNetworkID = -1;

    List<WifiConfiguration> connsLst = wifi.getConfiguredNetworks();
    int nConns = connsLst.size();
    for (int i = 0; i < nConns; i++) {

        foo = connsLst.get(i);
        if (foo.SSID.equalsIgnoreCase(wc.SSID)) {
            nNetworkID = foo.networkId;
            wc.networkId = foo.networkId;
            break;
        }
    }

    int res;

    if (nNetworkID != -1) {
        res = wifi.updateNetwork(wc);
    } else {
        res = wifi.addNetwork(wc);
    }

    Log.d("WifiPreference", "add Network returned " + res);

    boolean b = wifi.enableNetwork(res, true);
    Log.d("WifiPreference", "enableNetwork returned " + b);

    wifi.saveConfiguration();

    WifiInfo wi = wifi.getConnectionInfo();
    SupplicantState ss = wi.getSupplicantState();

    lcv = 0;
    lcv2 = 0;

    while (ss.compareTo(SupplicantState.COMPLETED) != 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (wi != null)
            wi = null;
        if (ss != null)
            ss = null;
        wi = wifi.getConnectionInfo();
        ss = wi.getSupplicantState();
        if (++lcv > 60) {
            if (++lcv2 > 5) {
                Toast.makeText(getApplication().getApplicationContext(),
                        "Unable to start and configure network", Toast.LENGTH_LONG).show();
                return (bRet);
            } else {
                Toast.makeText(getApplication().getApplicationContext(), "Resetting wifi interface",
                        Toast.LENGTH_LONG).show();
                if (wl != null)
                    wl.release();
                wifi.setWifiEnabled(false);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
                    Thread.yield();
                }

                wifi.setWifiEnabled(true);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
                    Thread.yield();
                }
                b = wifi.enableNetwork(res, true);
                Log.d("WifiPreference", "enableNetwork returned " + b);
                if (wl != null)
                    wl.acquire();
                lcv = 0;
            }
        }
    }

    lcv = 0;
    while (getLocalIpAddress() == null) {
        if (++lcv > 10000)
            return (bRet);
    }

    Toast.makeText(getApplication().getApplicationContext(), "Network started and configured",
            Toast.LENGTH_LONG).show();
    bRet = true;

    return (bRet);
}