List of usage examples for android.content Context WIFI_SERVICE
String WIFI_SERVICE
To view the source code for android.content Context WIFI_SERVICE.
Click Source Link
From source file:com.geryon.ocraa.MusicService.java
@Override public void onCreate() { // Log.i(TAG, "debug: Creating service"); utils = new Utilities(); // Create the Wifi lock (this does not acquire the lock, this just creates it) mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)) .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock"); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); // Create the retriever and start an asynchronous task that will prepare it. mRetriever = new MusicRetriever(getContentResolver()); (new PrepareMusicRetrieverTask(mRetriever, this)).execute(); // create the Audio Focus Helper, if the Audio Focus feature is available (SDK 8 or above) if (android.os.Build.VERSION.SDK_INT >= 8) mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this); else//from ww w. j a va 2s . co m mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus mDummyAlbumArt = BitmapFactory.decodeResource(getResources(), R.drawable.dummy_album_art); mMediaButtonReceiverComponent = new ComponentName(this, MusicIntentReceiver.class); }
From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java
@SuppressFBWarnings("REC_CATCH_EXCEPTION") @Nullable/*from w w w .ja v a 2 s. co m*/ @Override public IBinder onBind(Intent intent) { if (!mIsBound) { //TODO: check mBluetoothAdapter not null and/or check bluetooth is available - BluetoothUtils.isBluetoothAvailable() mBluetoothAdapter = BluetoothUtils.getBluetoothAdapter(HotspotManagerService.this); mOriginalBluetoothStatus = mBluetoothAdapter.isEnabled(); mOriginalBluetoothName = mBluetoothAdapter.getName(); //TODO: check mWifiManager not null and/or check bluetooth is available - WifiUtils.isWifiAvailable() // note we need the WifiManager for connecting to other hotspots regardless of whether we can create our own mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); // try to get the original state to restore later int wifiState = mWifiManager.getWifiState(); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLED: case WifiManager.WIFI_STATE_ENABLING: mOriginalWifiStatus = true; break; case WifiManager.WIFI_STATE_DISABLED: case WifiManager.WIFI_STATE_DISABLING: case WifiManager.WIFI_STATE_UNKNOWN: mOriginalWifiStatus = false; break; default: break; } // try to save the existing hotspot state if (CREATE_WIFI_HOTSPOT_SUPPORTED) { try { // TODO: is it possible to save/restore the original password? (WifiConfiguration doesn't hold the password) WifiConfiguration wifiConfiguration = WifiUtils.getWifiHotspotConfiguration(mWifiManager); mOriginalHotspotConfiguration = new ConnectionOptions(); mOriginalHotspotConfiguration.mName = wifiConfiguration.SSID; } catch (Exception ignored) { // note - need to catch Exception rather than ReflectiveOperationException due to our API level (requires 19) } } // set up background thread for message sending - see: https://medium.com/@ali.muzaffar/dc8bf1540341 mMessageThread = new HandlerThread("BTMessageThread"); mMessageThread.start(); mMessageThreadHandler = new Handler(mMessageThread.getLooper()); // set up listeners for network/bluetooth state changes IntentFilter intentFilter = new IntentFilter(); if (CREATE_WIFI_HOTSPOT_SUPPORTED) { intentFilter.addAction(HOTSPOT_STATE_FILTER); // Wifi hotspot states } intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); // Wifi on/off intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); // network connection/disconnection intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // Bluetooth on/off intentFilter.addAction(BluetoothDevice.ACTION_FOUND); // Bluetooth device found registerReceiver(mGlobalBroadcastReceiver, intentFilter); // listen for messages from our PluginMessageReceiver IntentFilter localIntentFilter = new IntentFilter(); localIntentFilter.addAction(PluginIntent.ACTION_MESSAGE_RECEIVED); localIntentFilter.addAction(PluginIntent.ACTION_STOP_PLUGIN); LocalBroadcastManager.getInstance(HotspotManagerService.this).registerReceiver(mLocalBroadcastReceiver, localIntentFilter); // listen for EventBus events (from wifi/bluetooth servers) if (!EventBus.getDefault().isRegistered(HotspotManagerService.this)) { EventBus.getDefault().register(HotspotManagerService.this); } mIsBound = true; } return mMessenger.getBinder(); }
From source file:com.google.android.gms.location.sample.geofencing.GeofenceTransitionsIntentService.java
private void scanWiFi() { // Launch wifiscanner the first time here (it will call the broadcast receiver above) WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); Boolean a = wm.startScan();/* w w w . j av a 2 s .c o m*/ }
From source file:com.owncloud.android.media.MediaService.java
/** * Initialize a service instance/* w ww . j a v a 2 s . c om*/ * * {@inheritDoc} */ @Override public void onCreate() { super.onCreate(); Log_OC.d(TAG, "Creating ownCloud media service"); mWifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)) .createWifiLock(WifiManager.WIFI_MODE_FULL, MEDIA_WIFI_LOCK_TAG); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Configure notification channel if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel mNotificationChannel; // The user-visible name of the channel. CharSequence name = getString(R.string.media_service_notification_channel_name); // The user-visible description of the channel. String description = getString(R.string.media_service_notification_channel_description); // Set importance low: show the notification everywhere but with no sound int importance = NotificationManager.IMPORTANCE_LOW; mNotificationChannel = new NotificationChannel(MEDIA_SERVICE_NOTIFICATION_CHANNEL_ID, name, importance); // Configure the notification channel. mNotificationChannel.setDescription(description); mNotificationManager.createNotificationChannel(mNotificationChannel); } mNotificationBuilder = new NotificationCompat.Builder(this); mNotificationBuilder.setColor(this.getResources().getColor(R.color.primary)); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); mBinder = new MediaServiceBinder(this); // add AccountsUpdatedListener mAccountManager = AccountManager.get(this); mAccountManager.addOnAccountsUpdatedListener(new OnAccountsUpdateListener() { @Override public void onAccountsUpdated(Account[] accounts) { // stop playback if account of the played media files was removed if (mAccount != null && !AccountUtils.exists(mAccount.name, MediaService.this)) { processStopRequest(false); } } }, null, false); }
From source file:org.openremote.android.test.console.net.ORNetworkCheckTest.java
private void enableWifi(boolean enable) { WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); if (enable && wifi.isWifiEnabled()) return;/*from ww w . j a va 2s . c o m*/ if (!enable && !wifi.isWifiEnabled()) return; if (enable && !wifi.isWifiEnabled()) { if (!wifi.setWifiEnabled(true)) fail("Cannot enable WiFi"); } else { wifi.disconnect(); wifi.setWifiEnabled(false); } // wait for it... for (int iterations = 0; iterations < 10; iterations++) { SystemClock.sleep(500); if (enable && wifi.isWifiEnabled()) break; if (!enable && !wifi.isWifiEnabled()) break; } }
From source file:com.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java
private String getWiFiBroadcastAddress(Context context) { String bcastaddr = null;//from w ww . ja v a 2s .c o m WifiManager mWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcp = mWifi.getDhcpInfo(); if (mWifi.isWifiEnabled() && dhcp != null) { int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; byte[] quads = new byte[4]; for (int k = 0; k < 4; k++) quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); try { bcastaddr = InetAddress.getByAddress(quads).getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } } return bcastaddr; }
From source file:com.example.android.listentgt.MainActivity.java
public boolean turnOnWifi(View view) { WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(!isWifiP2pEnabled); // true or false to activate/deactivate wifi isWifiP2pEnabled = !isWifiP2pEnabled; //update the device info ((DeviceListFragment) getFragment2()).updateThisDevice(((DeviceListFragment) getFragment2()).getDevice()); return true;//from ww w . java2 s . c o m }
From source file:co.shunya.gita.player.MusicService.java
@Override public void onCreate() { // Log.i(TAG, "debug: Creating service"); // Create the Wifi lock (this does not acquire the lock, this just creates it) mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)) .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock"); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); // create the Audio Focus Helper, if the Audio Focus feature is available (SDK 8 or above) if (android.os.Build.VERSION.SDK_INT >= 8) mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this); else/* w w w .j av a 2s. c o m*/ mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus mDummyAlbumArt = BitmapFactory.decodeResource(getResources(), R.drawable.krishnanarayana); mMediaButtonReceiverComponent = new ComponentName(this, MusicIntentReceiver.class); BusProvider.getMediaEventBus().register(this); }
From source file:com.qweex.callisto.podcast.DownloadTask.java
@Override protected Boolean doInBackground(String... params) { String TAG = StaticBlob.TAG(); boolean isVideo; Cursor current;/*from w w w. j a v a 2s. c om*/ long id = 0, identity = 0; Log.e(TAG, "Preparing to start: " + StaticBlob.databaseConnector.getActiveDownloads().getCount() + " downloads"); boolean canceled = false; while (StaticBlob.databaseConnector.getActiveDownloads().getCount() > 0) { if (isCancelled()) //Checks to see if it has been canceled by somewhere else { mNotificationManager.cancel(NOTIFICATION_ID); return false; } try { Cursor c = StaticBlob.databaseConnector.getActiveDownloads(); c.moveToFirst(); id = c.getLong(c.getColumnIndex("_id")); identity = c.getLong(c.getColumnIndex("identity")); isVideo = c.getInt(c.getColumnIndex("video")) > 0; current = StaticBlob.databaseConnector.getOneEpisode(identity); current.moveToFirst(); //Get info AudLink = current.getString(current.getColumnIndex("mp3link")); VidLink = current.getString(current.getColumnIndex("vidlink")); AudSize = current.getLong(current.getColumnIndex("mp3size")); VidSize = current.getLong(current.getColumnIndex("vidsize")); Title = current.getString(current.getColumnIndex("title")); Date = current.getString(current.getColumnIndex("date")); Show = current.getString(current.getColumnIndex("show")); Date = StaticBlob.sdfFile.format(StaticBlob.sdfRaw.parse(Date)); //Getting target Target = new File(StaticBlob.storage_path + File.separator + Show); Target.mkdirs(); if (Title.indexOf("|") > 0) Title = Title.substring(0, Title.indexOf("|")); Title = Title.trim(); AudFile = new File(Target, Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(AudLink)); if (VidLink != null) VidFile = new File(Target, Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(VidLink)); Target = isVideo ? VidFile : AudFile; //Prepare the HTTP Log.i(TAG, "Path: " + Target.getPath()); URL url = new URL(isVideo ? VidLink : AudLink); Log.i(TAG, "Starting download: " + url.toString()); Log.i(TAG, "Opening the connection..."); HttpURLConnection ucon = (HttpURLConnection) url.openConnection(); String lastModified = ucon.getHeaderField("Last-Modified"); ucon = (HttpURLConnection) url.openConnection(); if (Target.exists()) { ucon.setRequestProperty("Range", "bytes=" + Target.length() + "-"); ucon.setRequestProperty("If-Range", lastModified); } ucon.setReadTimeout(TIMEOUT_CONNECTION); ucon.setConnectTimeout(TIMEOUT_SOCKET); ucon.connect(); //Notification mBuilder.setProgress(100, 0, true) .setContentTitle(this.context.getResources().getString(R.string.downloading) + " " + StaticBlob.current_download + " " + this.context.getResources().getString(R.string.of) + " " + downloading_count) .setContentText(Show + ": " + Title); // Displays the progress bar for the first time. mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); //Actually do the DLing InputStream is = ucon.getInputStream(); TotalSize = ucon.getContentLength() + Target.length(); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); FileOutputStream outStream; byte buff[]; Log.i(TAG, "mmk skipping the downloaded portion..." + Target.length() + " of " + TotalSize); if (Target.exists()) //Append if it exists outStream = new FileOutputStream(Target, true); else outStream = new FileOutputStream(Target); buff = new byte[5 * 1024]; Log.i(TAG, "Getting content length (size)"); int len = 0; long downloadedSize = Target.length(), percentDone = 0; //SPEED_COUNT == the number of times through the buffer loop to go through before updating the speed // currentDownloadLoopIndex == ??? // lastTime == The time that the last speed was calculated at // all_spds == All speeds tabulated thus far from currentDownloadLoopIndex to SPEED_COUNT // avg_speed == the average speed when SPEED_COUNT is reached int SPEED_COUNT = 200, currentDownloadLoopIndex = 0; long lastTime = (new java.util.Date()).getTime(), all_spds = 0; double avg_speed = 0; DecimalFormat df = new DecimalFormat("#.##"); //Wifi lock WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (DownloadList.Download_wifiLock == null) DownloadList.Download_wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "Callisto_download"); if (!DownloadList.Download_wifiLock.isHeld()) DownloadList.Download_wifiLock.acquire(); Log.i(TAG, "FINALLY starting the download"); inner_failures = 0; //-----------------Here is where the actual downloading happens---------------- while (len != -1) { Cursor active = StaticBlob.databaseConnector.getActiveDownloads(); if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0) canceled = true; else { active.moveToFirst(); canceled = active.getLong(active.getColumnIndex("identity")) != identity; } if (canceled) { Log.i(TAG, "Download has been canceled, deleting."); Target.delete(); break; } if (isCancelled()) { mNotificationManager.cancel(NOTIFICATION_ID); return false; } try { len = inStream.read(buff); if (len == -1) break; outStream.write(buff, 0, len); downloadedSize += len; percentDone = downloadedSize * 100; percentDone /= TotalSize; //Add to the average speed long temp_spd = 0; long time_diff = ((new java.util.Date()).getTime() - lastTime); if (time_diff > 0) { temp_spd = len * 100 / time_diff; currentDownloadLoopIndex++; all_spds += temp_spd; lastTime = (new java.util.Date()).getTime(); } } catch (IOException e) { Log.e(TAG + ":IOException", "IO is a moon - " + inner_failures); inner_failures++; if (inner_failures == INNER_LIMIT) break; try { Thread.sleep(500); } catch (InterruptedException e1) { } //Add failure to average currentDownloadLoopIndex++; lastTime = (new java.util.Date()).getTime(); } catch (Exception e) { Log.e(TAG + ":??Exception", e.getClass() + " : " + e.getMessage()); try { Thread.sleep(500); } catch (InterruptedException e1) { } //Add failure to average currentDownloadLoopIndex++; lastTime = (new java.util.Date()).getTime(); } //If the time is right, get the average if (currentDownloadLoopIndex >= SPEED_COUNT) { avg_speed = all_spds * 1.0 / currentDownloadLoopIndex / 100; all_spds = 0; currentDownloadLoopIndex = 0; if (DownloadList.thisInstance != null) { DownloadList.thisInstance.runOnUiThread( DownloadList.thisInstance.new DownloadProgressUpdater((int) (TotalSize / 1000), (int) (downloadedSize / 1000))); } mBuilder.setProgress((int) (TotalSize / 1000), (int) (downloadedSize / 1000), false) .setContentTitle(this.context.getResources().getString(R.string.downloading) + " " + StaticBlob.current_download + " " + this.context.getResources().getString(R.string.of) + " " + downloading_count + " - " + percentDone + "% (" + df.format(avg_speed) + "kb/s)") .setContentText(Show + ": " + Title); // Displays the progress bar for the first time. mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } } // END download of single file outStream.flush(); outStream.close(); inStream.close(); if (inner_failures == INNER_LIMIT) { throw new Exception("Inner exception has passed " + INNER_LIMIT); } Cursor active = StaticBlob.databaseConnector.getActiveDownloads(); if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0) canceled = true; else { active.moveToFirst(); canceled = active.getLong(active.getColumnIndex("identity")) != identity; } if (!canceled) { Log.i(TAG, "Trying to finish with " + Target.length() + "==" + TotalSize); if (Target.length() == TotalSize) { StaticBlob.current_download++; Log.i(TAG, (inner_failures < INNER_LIMIT ? "Successfully" : "FAILED") + " downloaded to : " + Target.getPath()); //Move the download from active to completed. StaticBlob.databaseConnector.markDownloadComplete(id); Log.i(TAG, " " + DownloadList.rebuildHeaderThings); if (DownloadList.rebuildHeaderThings != null) DownloadList.rebuildHeaderThings.sendEmptyMessage(0); boolean queue = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean("download_to_queue", false); if (queue) { StaticBlob.databaseConnector.appendToQueue(identity, false, isVideo); StaticBlob.playerInfo.update(context); } //Episode Desc if (EpisodeDesc.currentInstance != null) EpisodeDesc.currentInstance.determineButtons(); //ShowList if (ShowList.thisInstance != null && ShowList.thisInstance.currentDownloadItem != null) { ShowList.thisInstance.runOnUiThread(ShowList.thisInstance.new updateBoldOrItalic(id, ShowList.thisInstance.currentDownloadItem, AudFile, VidFile, AudSize, VidSize)); ShowList.thisInstance.currentDownloadItem = null; } } } else Target.delete(); } catch (ParseException e) { Log.e(TAG + ":ParseException", "Error parsing a date from the SQLite db: "); Log.e(TAG + ":ParseException", Date); Log.e(TAG + ":ParseException", "(This should never happen)."); outer_failures++; e.printStackTrace(); } catch (Exception e) { outer_failures++; Log.e(TAG + ":Exception " + e.getClass(), "[" + outer_failures + "] Msg: " + e.getMessage()); e.printStackTrace(); try { Thread.sleep(1000); } catch (InterruptedException e1) { } } if (outer_failures == OUTER_LIMIT) { boolean quit = false; //if(quit = aDownloads.charAt(1)=='x') // aDownloads = aDownloads.replaceAll("x",""); quit = true; if (DownloadList.rebuildHeaderThings != null) DownloadList.rebuildHeaderThings.sendEmptyMessage(0); failed++; outer_failures = 0; if (quit) break; } } Log.i(TAG, "Finished Downloading"); if (DownloadList.thisInstance != null) DownloadList.thisInstance.updateMenu(); //Wifi lock if (DownloadList.Download_wifiLock != null && DownloadList.Download_wifiLock.isHeld()) DownloadList.Download_wifiLock.release(); //Notification mNotificationManager.cancel(NOTIFICATION_ID); if (downloading_count > 0) { mBuilder.setProgress(100, 0, false) .setContentTitle("Finished downloading " + downloading_count + " files"); if (failed > 0) mBuilder.setContentText(failed + " failed, try them again later"); mBuilder.setAutoCancel(true); mBuilder.setOngoing(false); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); StaticBlob.current_download = 1; downloading_count = 0; } else { StaticBlob.current_download = 1; downloading_count = 0; return false; } return true; }
From source file:org.basdroid.common.NetworkUtils.java
public static String getMacAddressFromNetworkInterface(final Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); // Convert little-endian to big-endianif needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); }//from w w w . j a v a 2s . c o m byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); String result; try { InetAddress addr = InetAddress.getByAddress(bytes); NetworkInterface netInterface = NetworkInterface.getByInetAddress(addr); Log.d(TAG, "Wifi netInterface.getName() = " + netInterface.getName()); byte[] mac = netInterface.getHardwareAddress(); if (mac == null || mac.length == 0) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) { buf.append(String.format("%02X:", mac[idx])); } if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } catch (UnknownHostException ex) { Log.e(TAG, "getMacAddressFromNetworkInterface() Unknown host.", ex); result = null; } catch (SocketException ex) { Log.e(TAG, "getMacAddressFromNetworkInterface() Socket exception.", ex); result = null; } catch (Exception ex) { Log.e(TAG, "getMacAddressFromNetworkInterface() Exception.", ex); result = null; } return result; }