List of usage examples for android.net ConnectivityManager TYPE_WIFI
int TYPE_WIFI
To view the source code for android.net ConnectivityManager TYPE_WIFI.
Click Source Link
From source file:com.putlocker.upload.DownloadService.java
@Override protected void onHandleIntent(Intent intent) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Download Wakelock"); wl.acquire();/*from w ww .j av a 2 s.co m*/ ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); WifiLock wifiLock = null; // We only want to aquire the wifi wake lock if (mWifi.isConnected()) { wifiLock = ((WifiManager) this.getSystemService(Context.WIFI_SERVICE)) .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "WlanSilencerScanLock"); wifiLock.acquire(); } if (intent.hasExtra(JOB_EXTRA_DOWNLOAD)) { handleDownloadIntent(intent); } else { handleUploadIntent(intent); } if (wifiLock != null && wifiLock.isHeld()) { wifiLock.release(); } wl.release(); }
From source file:org.eeiiaa.wifi.WifiConnector.java
@Override public void onReceive(Context context, Intent intent) { // handle stuff related to scanning requested when: // normal scan is issued // when forgetting a network and re-connecting to a previously configured // existing one // when connecting and need a scan to verify connection can be established Log.i(TAG, "action: " + intent.getAction()); if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) && (mWaitingScan || mConnecting)) { // forgetting current and reconnecting to highest priority existing // network Log.i(TAG, "ACTION SCAN: mWaitingScan:" + mWaitingScan + " connecting " + mConnecting); // normal scan request if (mWaitingScan) { String json = new String(); switch (scanResultOption) { case GET_ALL: json = getScannedNetworksAllJSON(); break; case GET_BSSID_ONLY: json = getScannedNetworksJSON(); break; }/* ww w .j a v a2s . co m*/ mScanListener.scanResultsJSON(json); mWaitingScan = false; // scan is done - unregister mContext.unregisterReceiver(this); Log.i(TAG, "processing scan results as JSON"); } if (mConnecting && !mWaitingConnection) { // look for the network we want to connect to in the scanned results ScanResult scannedNet = searchNetwork(mNetssid); if (scannedNet == null) { Log.i(TAG, "ssid not found...: " + mNetssid); mConnecting = false; mContext.unregisterReceiver(this); notifyConnectionFailed(); return; // didn't find requested network noting to connect } WifiConfiguration configuredNet = searchConfiguration(scannedNet); boolean result_ok = false; if (configuredNet != null) { // configuration exits connect to a configured network mWaitingConnection = true; result_ok = Wifi.connectToConfiguredNetwork(mContext, mWifiMgr, configuredNet, false); Log.i(TAG, "configuration exits connect to a configured network"); } else { // configure and connect to network mWaitingConnection = true; result_ok = Wifi.connectToNewNetwork(mContext, mWifiMgr, scannedNet, mPwd, MAX_OPEN_NETS); Log.i(TAG, "configure and connect to network"); } // failed to connect - unregister and notify if (!result_ok) { mContext.unregisterReceiver(this); mWaitingConnection = false; mConnecting = false; Log.e(TAG, "error connecting Wifi.connect returned error"); notifyConnectionFailed(); } } } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) && (mConnected || (mConnecting && mWaitingConnection))) { Log.i(TAG, "ACTION CONNECTIVITY: mWaitingScan:" + mWaitingScan + " forgetting: " + forgetting_ + " connecting " + mConnecting); NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (!mConnected && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) { if (mWifiMgr.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) { Log.i(TAG, " getConnectionInfo: " + mWifiMgr.getConnectionInfo() + " getSSID: " + mWifiMgr.getConnectionInfo().getSSID()); String connectionSsid = unQuote(mWifiMgr.getConnectionInfo().getSSID()); // when phone turns into AP mode, wifimgr returns null... // fail protection for such cases... if (connectionSsid != null) { Log.i(TAG, "mNetssid: |" + mNetssid + "| connectionSsid |" + connectionSsid + "|"); if (connectionSsid.equals(mNetssid)) { mConnected = true; mConnecting = false; mWaitingConnection = false; forgetting_ = false; Log.i(TAG, "VERIFIED SUCCESSFUL CONNECTION to: " + mNetssid); // connection done notify - do not unregister to get disconnection detected notifyConnectionListener(); } } } } else if (mConnected && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) { Log.i(TAG, "network is disconnected..."); // Wifi is disconnected mConnected = false; mWaitingConnection = false; if (mDataListener != null && used_ != null) { used_.updateUsageCounters(); transmitted = used_.getWifiTransmitted(); received = used_.getWifiReceived(); } // network lost was not expected (when forgetting we expect network to // be lost) if (!forgetting_) { Log.i(TAG, "network lost " + networkInfo); notifyNetworkLost(networkInfo); mContext.unregisterReceiver(this); } else { Log.i(TAG, "network lost when forgetting " + networkInfo); } } Log.i(TAG, "end of CONNECTIVITY_ACTION"); } }
From source file:org.zywx.wbpalmstar.platform.push.PushService.java
private void onReceive() { final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(CONNECTIVITY_CHANGE_ACTION); registerReceiver(new BroadcastReceiver() { @Override/*from www . jav a2 s . c om*/ public void onReceive(Context context, Intent intent) { if ("android.intent.action.SCREEN_OFF".equals(intent.getAction())) { if (isTemporary) { sleepTime = 1000 * 60 * 2; } else { sleepTime = 1000 * 60 * 15; } notifiTimer(); } else if ("android.intent.action.SCREEN_ON".equals(intent.getAction())) { if (isTemporary) { sleepTime = 1000 * 30; } else { sleepTime = 1000 * 60 * 2; } notifiTimer(); } if (TextUtils.equals(intent.getAction(), CONNECTIVITY_CHANGE_ACTION)) { ConnectivityManager mConnMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (mConnMgr != null) { NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // ?? if (aActiveInfo != null && aActiveInfo.isConnectedOrConnecting()) { if (!isSend && aActiveInfo.getType() == ConnectivityManager.TYPE_WIFI) { // udpReg(); // notifiUDPTimer(); isSend = true; } } else { isSend = false; } } else { isSend = false; } } } }, filter); }
From source file:com.miz.functions.MizLib.java
/** * Determines if the device is currently connected to a WiFi or Ethernet network * @param c - Context of the application * @return True if connected to a network, else false *//*from ww w .j a v a 2 s . c om*/ public static boolean isWifiConnected(Context c) { if (c != null) { boolean disableEthernetWiFiCheck = PreferenceManager.getDefaultSharedPreferences(c) .getBoolean(DISABLE_ETHERNET_WIFI_CHECK, false); if (disableEthernetWiFiCheck) return isOnline(c); ConnectivityManager connManager = (ConnectivityManager) c .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] connections = connManager.getAllNetworkInfo(); int count = connections.length; for (int i = 0; i < count; i++) if (connections[i] != null && connections[i].getType() == ConnectivityManager.TYPE_WIFI && connections[i].isConnectedOrConnecting() || connections[i] != null && connections[i].getType() == ConnectivityManager.TYPE_ETHERNET && connections[i].isConnectedOrConnecting()) return true; } return false; }
From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java
/** * This is called when activity is created. Initializes the state, performs network * state based selection for app initialization and starts the widget list *//*from ww w . j a va 2s .co m*/ @Override public void onCreate(Bundle savedInstanceState) { Log.d("OpenHABWidgetListActivity", "onCreate"); // Set default values, false means do it one time during the very first launch PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Set non-persistant HABDroid version preference to current version from application package try { PreferenceManager.getDefaultSharedPreferences(this).edit().putString("default_openhab_appversion", getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit(); } catch (NameNotFoundException e1) { if (e1 != null) Log.d(TAG, e1.getMessage()); } // Set the theme to one from preferences Util.setActivityTheme(this); // Fetch openHAB service type name from strings.xml openHABServiceType = getString(R.string.openhab_service_type); // Enable progress ring bar requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setProgressBarIndeterminateVisibility(true); // Initialize crittercism reporting JSONObject crittercismConfig = new JSONObject(); try { crittercismConfig.put("shouldCollectLogcat", true); } catch (JSONException e) { if (e.getMessage() != null) Log.e(TAG, e.getMessage()); else Log.e(TAG, "Crittercism JSON exception"); } Crittercism.init(getApplicationContext(), "5117659f59e1bd4ba9000004", crittercismConfig); // Initialize activity view super.onCreate(savedInstanceState); setContentView(R.layout.openhabwidgetlist); // Disable screen timeout if set in preferences SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); if (settings.getBoolean("default_openhab_screentimeroff", false)) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } // Check if we got all needed permissions PackageManager pm = getPackageManager(); if (!(pm.checkPermission(permission.CHANGE_WIFI_MULTICAST_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED)) { showAlertDialog(getString(R.string.erorr_no_wifi_mcast_permission)); serviceDiscoveryEnabled = false; } if (!(pm.checkPermission(permission.ACCESS_WIFI_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED)) { showAlertDialog(getString(R.string.erorr_no_wifi_state_permission)); serviceDiscoveryEnabled = false; } // Get username/password from preferences openHABUsername = settings.getString("default_openhab_username", null); openHABPassword = settings.getString("default_openhab_password", null); // Create new data source and adapter and set it to list view openHABWidgetDataSource = new OpenHABWidgetDataSource(); openHABWidgetAdapter = new OpenHABWidgetAdapter(OpenHABWidgetListActivity.this, R.layout.openhabwidgetlist_genericitem, widgetList); getListView().setAdapter(openHABWidgetAdapter); // Set adapter parameters openHABWidgetAdapter.setOpenHABUsername(openHABUsername); openHABWidgetAdapter.setOpenHABPassword(openHABPassword); // Enable app logo as home button this.getActionBar().setHomeButtonEnabled(true); // Check if we have openHAB page url in saved instance state? if (savedInstanceState != null) { displayPageUrl = savedInstanceState.getString("displayPageUrl"); openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl"); sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl"); openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl); } // Check if this is a launch from myself (drill down navigation) if (getIntent() != null) { if (getIntent().getAction() != null) { if (getIntent().getAction().equals("org.openhab.habdroid.ui.OpwnHABWidgetListActivity")) { displayPageUrl = getIntent().getExtras().getString("displayPageUrl"); openHABBaseUrl = getIntent().getExtras().getString("openHABBaseUrl"); sitemapRootUrl = getIntent().getExtras().getString("sitemapRootUrl"); this.setTitle(getIntent().getExtras().getString("pageTitle")); openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl); } } } // If yes, then just go to it (means restore activity from it's saved state) if (displayPageUrl.length() > 0) { Log.d(TAG, "displayPageUrl = " + displayPageUrl); showPage(displayPageUrl, false); // If not means it is a clean start } else { if (getIntent() != null) { Log.i(TAG, "Launch intent = " + getIntent().getAction()); // If this is a launch through NFC tag reading if (getIntent().getAction() != null) { if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) { // Save url which we got from NFC tag nfcTagData = getIntent().getDataString(); } } } // If we are in demo mode, ignore all settings and use demo url from strings if (settings.getBoolean("default_openhab_demomode", false)) { openHABBaseUrl = getString(R.string.openhab_demo_url); Log.i(TAG, "Demo mode, connecting to " + openHABBaseUrl); Toast.makeText(getApplicationContext(), getString(R.string.info_demo_mode), Toast.LENGTH_LONG) .show(); showTime(); } else { openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_url", "")); // Check if we have a direct URL in preferences, if yes - use it if (openHABBaseUrl.length() > 0) { Log.i(TAG, "Connecting to configured URL = " + openHABBaseUrl); Toast.makeText(getApplicationContext(), getString(R.string.info_conn_url), Toast.LENGTH_SHORT) .show(); showTime(); } else { // Get current network information ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo != null) { Log.i(TAG, "Network is connected"); // If network is mobile, try to use remote URL if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE || serviceDiscoveryEnabled == false) { if (!serviceDiscoveryEnabled) { Log.i(TAG, "openHAB discovery is disabled"); } else { Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")"); } openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_alturl", "")); // If remote URL is configured if (openHABBaseUrl.length() > 0) { Toast.makeText(getApplicationContext(), getString(R.string.info_conn_rem_url), Toast.LENGTH_SHORT).show(); Log.i(TAG, "Connecting to remote URL " + openHABBaseUrl); showTime(); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_url), Toast.LENGTH_LONG).show(); } // If network is WiFi or Ethernet } if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { Log.i(TAG, "Network is WiFi or Ethernet"); // Start service discovery this.serviceResolver = new AsyncServiceResolver(this, openHABServiceType); progressDialog = ProgressDialog.show(this, "", "Discovering openHAB. Please wait...", true); this.serviceResolver.start(); // We don't know how to handle this network type } else { Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported"); } // Network is not available } else { Log.i(TAG, "Network is not available"); Toast.makeText(getApplicationContext(), getString(R.string.error_network_not_available), Toast.LENGTH_LONG).show(); } } } } }
From source file:org.mozilla.gecko.sync.setup.activities.SetupSyncActivity.java
private boolean hasInternet() { Logger.debug(LOG_TAG, "Checking internet connectivity."); ConnectivityManager connManager = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifi.isConnected() || mobile.isConnected()) { Logger.debug(LOG_TAG, "Internet connected."); return true; }//from www.j a v a 2s .c o m return false; }
From source file:com.starup.traven.travelkorea.ImageGridFragment.java
private void updateConnectedFlags() { ConnectivityManager connMgr = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeInfo = connMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI; mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE; } else {/* w ww .j a v a2s .c om*/ wifiConnected = false; mobileConnected = false; } }
From source file:com.heneryh.aquanotes.io.ApexExecutor.java
public void feedCycle(Cursor cursor, int cycleNumber) throws HandlerException { /**// w w w . j a v a2 s.c o m * The cursor contains all of the controller details. */ String lanUri = cursor.getString(ControllersQuery.LAN_URL); String wanUri = cursor.getString(ControllersQuery.WAN_URL); String user = cursor.getString(ControllersQuery.USER); String pw = cursor.getString(ControllersQuery.PW); String ssid = cursor.getString(ControllersQuery.WIFI_SSID); String model = cursor.getString(ControllersQuery.MODEL); String apexBaseURL; // Determine if we are on the LAN or WAN and then use appropriate URL // Uhg, WifiManager stuff below crashes if wifi not enabled so first we have to check if on wifi ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cm.getActiveNetworkInfo(); if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo = wm.getConnectionInfo(); // somewhere read this was a quoted string but appears not to be if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class apexBaseURL = lanUri; } else { apexBaseURL = wanUri; } } else { apexBaseURL = wanUri; } // for this function we need to append to the URL. I should really // check if the "/" was put on the end by the user here to avoid // possible errors. if (!apexBaseURL.endsWith("/")) { String tmp = apexBaseURL + "/"; apexBaseURL = tmp; } // oh, we should also check if it starts with an "http://" if (!apexBaseURL.toLowerCase().startsWith("http://")) { String tmp = "http://" + apexBaseURL; apexBaseURL = tmp; } // we should also check if it ends with an "status.sht" on the end and remove it. // This used to be common for both the Apex and ACiii but during // the 4.04 beta Apex release it seemed to have broke and forced // me to use status.sht for the Apex. Maybe it was fixed but I // haven't checked it. // edit - this was not needed for the longest while but now that we are pushing just one // outlet, the different methods seem to be needed again. Really not sure why. String apexURL; if (model.equalsIgnoreCase("AC4")) { apexURL = apexBaseURL + "status.sht"; } else { apexURL = apexBaseURL + "cgi-bin/status.cgi"; } //Create credentials for basic auth // create a basic credentials provider and pass the credentials // Set credentials provider for our default http client so it will use those credentials UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw); BasicCredentialsProvider cP = new BasicCredentialsProvider(); cP.setCredentials(AuthScope.ANY, c); ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP); // Build the POST update which looks like this: // form="status" // method="post" // action="status.sht" // // name="T5s_state", value="0" (0=Auto, 1=Man Off, 2=Man On) // submit -> name="Update", value="Update" // -- or // name="FeedSel", value="0" (0=A, 1=B) // submit -> name="FeedCycle", value="Feed" // -- or // submit -> name="FeedCycle", value="Feed Cancel" HttpPost httppost = new HttpPost(apexURL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // Add your data nameValuePairs.add(new BasicNameValuePair("name", "status")); nameValuePairs.add(new BasicNameValuePair("method", "post")); if (model.equalsIgnoreCase("AC4")) { nameValuePairs.add(new BasicNameValuePair("action", "status.sht")); } else { nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi")); } String cycleNumberString = Integer.toString(cycleNumber).trim(); if (cycleNumber < 4) { nameValuePairs.add(new BasicNameValuePair("FeedSel", cycleNumberString)); nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed")); } else { nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed Cancel")); } nameValuePairs.add(new BasicNameValuePair("Update", "Update")); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse resp = mHttpClient.execute(httppost); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine()); } } catch (HandlerException e) { throw e; } catch (ClientProtocolException e) { throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e); } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e); } }
From source file:net.net76.lifeiq.TaskiQ.RegisterActivity.java
public boolean isNetworkAvaliable(Context ctx) { ConnectivityManager connectivityManager = (ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE); if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED) || (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) { return true; } else {//w ww .ja v a 2 s . c o m return false; } }
From source file:ca.zadrox.dota2esportticker.service.UpdateMatchService.java
private boolean wifiUpdate() { ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean wifiState = true; if (PrefUtils.updateOnWifiOnly(this)) { wifiState = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; }// w w w .ja v a2s.c o m return wifiState; }