/// <summary>
        /// On create simply detect some of our managers
        /// </summary>
        public override void OnCreate()
        {
            base.OnCreate();
            //Find our audio and notificaton managers
            audioManager = (AudioManager)GetSystemService(AudioService);
            wifiManager = (WifiManager)GetSystemService(WifiService);

			remoteComponentName = new ComponentName(PackageName, new RemoteControlBroadcastReceiver().ComponentName);
        }
 /// <summary>
 /// On create simply detect some of our managers
 /// </summary>
 public override void OnCreate()
 {
     base.OnCreate();
     //Find our audio and notificaton managers
     AudioManager = (AudioManager) GetSystemService(AudioService);
     wifiManager = (WifiManager) GetSystemService(WifiService);
 }
 private static void EnsureDifferentNetworksNotActive(WifiManager wifiManager, WifiConfiguration network)
 {
     var differentActiveNetwork = wifiManager.ConfiguredNetworks
         .Where(x => x.Ssid != network.Ssid)
         .FirstOrDefault(x => x.StatusField == WifiStatus.Current);
     if (differentActiveNetwork != null)
         throw new InvalidOperationException($"Different network {differentActiveNetwork.Ssid} is active");
 }
Пример #4
1
 public Wifi()
 {
     Mvx.CallbackWhenRegistered<IMvxAndroidGlobals>(x =>
     {
         _manager =
             x.ApplicationContext.GetSystemService(Context.WifiService)
                 .JavaCast<WifiManager>();
     });
 }
        /// <summary> Get existing matching network </summary>
        private static WifiConfiguration GetConfiguredNetwork(WifiManager wifiManager, Ssid ssid)
        {
            var existingNetwork = wifiManager.ConfiguredNetworks
                .FirstOrDefault(x => x.Ssid == ssid.Quoted);
            Logger.Verbose(existingNetwork != null
                ? $"Found existing network {ssid}"
                : $"Existing network {ssid} not found");

            if (existingNetwork == null)
                throw new InvalidOperationException($"Network {ssid} not configured");
            
            return existingNetwork;
        }
Пример #6
1
        public override void OnCreate ()
        {
            base.OnCreate ();

            _episodeProgressUpdateTimer = new Timer (
                o => UpdateEpisodeCurrentTimeIfPlaying(),
                null,
                0,
                EPISODE_CURRENT_TIME_UPDATE_INTERVAL
            );

            // Find our audio and notificaton managers
            _audioManager = (AudioManager)GetSystemService (AudioService);
            _wifiManager = (WifiManager)GetSystemService (WifiService);
        }
Пример #7
1
        public cTestInet(Context c)
        {
            m_Contexto = c;

            m_ConexionINet = false;
            m_TipoConexion = enumTipoConexion.SINCONEXION;
            m_NombreConexion = string.Empty;
            m_VelocidadSubidaReal =  0d;
            m_VelocidadSubidaTeorica = 0d;
            m_VelocidadBajadaReal = 0d;
            m_VelocidadBajadaTeorica = 0d;

            m_GsmSignalStrengthListener = new GsmSignalStrengthListener();
            m_GsmSignalStrengthListener.SignalStrengthChanged += HandleSignalStrengthChanged;

            m_TelefonoManager = (TelephonyManager) m_Contexto.GetSystemService(Context.TelephonyService);
            m_TelefonoManager.Listen(m_GsmSignalStrengthListener, PhoneStateListenerFlags.SignalStrengths);

            m_ConnectivityManager = (ConnectivityManager) m_Contexto.GetSystemService(Context.ConnectivityService);
            m_WifiManager = (WifiManager) m_Contexto.GetSystemService(Context.WifiService);
        }
 private static void Reconnect(WifiManager wifiManager)
 {
     if (!wifiManager.Reconnect())
         throw new InvalidOperationException("Reconnection failed");
 }
    /// <summary>
    /// Dispose
    /// </summary>
    /// <param name="disposing"></param>
    public override void Dispose(bool disposing)
    {
      if (!disposed)
      {
        if (disposing)
        {



          if (receiver != null)
            Application.Context.UnregisterReceiver(receiver);

          ConnectivityChangeBroadcastReceiver.ConnectionChanged = null;
          if (wifiManager != null)
          {
            wifiManager.Dispose();
            wifiManager = null;
          }

          if (connectivityManager != null)
          {
            connectivityManager.Dispose();
            connectivityManager = null;
          }

        }

        disposed = true;
      }

      base.Dispose(disposing);
    }
Пример #10
0
 private void finallyConnect(string networkPass, string networkSSID)
 {
     try
     {
         using (Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)ApplicationContext.GetSystemService(Context.WifiService))
         {
             if (wifi != null && wifi.IsWifiEnabled)
             {
                 using (WifiConfiguration wifiConfig = new WifiConfiguration())
                 {
                     wifiConfig.Ssid         = "\"" + networkSSID + "\""; //string.Format("\"%s\"", networkSSID);
                     wifiConfig.PreSharedKey = "\"" + networkPass + "\""; // string.Format("\"%s\"", networkPass);
                     int netId = wifi.AddNetwork(wifiConfig);
                     wifi.Disconnect();
                     wifi.EnableNetwork(netId, true);
                     wifi.Reconnect();
                     using (WifiConfiguration conf = new WifiConfiguration())
                     {
                         conf.Ssid         = "\"" + networkSSID + "\"";
                         conf.PreSharedKey = "\"" + networkPass + "\"";
                         wifi.AddNetwork(conf);
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
Пример #11
0
 public IPAddress GetBroadcastAddress(WifiManager wifi)
 {
     var dhcp = wifi.DhcpInfo;
     var broadcast = (dhcp.IpAddress & dhcp.Netmask) | ~dhcp.Netmask;
     var quads = new byte[4];
     for (var k = 0; k < 4; k++) quads[k] = (byte)((broadcast >> k * 8) & 0xFF);
     return new IPAddress(quads);
 }
Пример #12
0
 public NetworkInterface()
 {
     var context = Application.Context.ApplicationContext;
     wifi = (WifiManager)context.GetSystemService(Context.WifiService);
 }
        /*
         * Create Method
         * Fires when the activity is started
         */
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            //setting the main layout Main.xml
            SetContentView(Resource.Layout.Main);

            //Getting telephony and wifi information from the system service
            telephonyManager = (TelephonyManager)this.GetSystemService(Context.TelephonyService);
            wifiManager= (WifiManager)this.GetSystemService(Service.WifiService);

            //Declaring the command ubttons
            var cmd_SensorStatus = FindViewById<Button> (Resource.Id.sensorStatusButton);
            var cmd_Calculate = FindViewById<Button> (Resource.Id.cmdCalculate);

            //Adding text view by id
            _deviceIdTextView = FindViewById<TextView> (Resource.Id.textDeviceID);

            batteryStatusTextView = FindViewById<TextView> (Resource.Id.textBatteryStatus);
            batteryLevelTextView = FindViewById<TextView> (Resource.Id.textBatteryLevel);
            batteryVoltageTextView = FindViewById<TextView> (Resource.Id.textBatteryVoltage);
            batteryTemperatureTextView = FindViewById<TextView> (Resource.Id.textBatteryTemperature);
            batteryTechnologyTextView = FindViewById<TextView> (Resource.Id.textBatteryTechnology);

            _IpTextView = FindViewById<TextView> (Resource.Id.textIP);
            //Adding text to the text views from device information
            _deviceIdTextView.Text = telephonyManager.DeviceId.ToString ();

            //Registering battery related information
            registerBatteryLevelReceiver();

            device_ID = _deviceIdTextView.Text;
            device_Info = Build.Manufacturer.ToString ()+ " " + Build.Model.ToString ();

            batteryStatusTextView.Text = battery_status;
            batteryLevelTextView.Text = battery_level.ToString();
            batteryVoltageTextView.Text = battery_voltage.ToString();
            batteryTemperatureTextView.Text = battery_temperature.ToString();
            batteryTechnologyTextView.Text = battery_Technology;

            //locationInfo = telephonyManager.CellLocation.ToString ();

            //Getting localip address
            int ip = wifiManager.ConnectionInfo.IpAddress;
            _IpTextView.Text = string.Format("{0}.{1}.{2}.{3}",(ip & 0xff),(ip >> 8 & 0xff),(ip >> 16 & 0xff),(ip >> 24 & 0xff));

            //Adding even listeners buttons
            cmd_SensorStatus.Click += (object sender, EventArgs e) => {sensorStatusButtonClick();};
            cmd_Calculate.Click += (object sender, EventArgs e) => {calculateButtonClick();};
        }
Пример #14
0
        protected override void OnResume()
        {
            try
            {
                string status = "WIFI NETWORKS: ";
                string SSID = "";
                using (Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)ApplicationContext.GetSystemService(Context.WifiService))
                {
                    if (wifi != null)
                    {
                        if (wifi.IsWifiEnabled)
                        {
                            using (WifiInfo wifiInfo = wifi.ConnectionInfo)
                            {
                                if (wifiInfo != null)
                                {
                                    using (NetworkInfo.DetailedState state = WifiInfo.GetDetailedStateOf(wifiInfo.SupplicantState))
                                    {
                                        if (state == NetworkInfo.DetailedState.Connected || state == NetworkInfo.DetailedState.ObtainingIpaddr)
                                        {
                                            SSID = wifiInfo.SSID;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            wifi.SetWifiEnabled(true);
                        }

                using (ConnectivityManager cm = (ConnectivityManager)GetSystemService(Context.ConnectivityService))
                {
                    if (cm != null)
                    {
                        using (NetworkInfo activeNetwork = cm.ActiveNetworkInfo)
                        {
                            if (activeNetwork != null && activeNetwork.IsConnected)
                            {
                                SSID = SSID.Replace("\"", "");
                                status = ": CONNECTED TO INTERNET. Select a network from the list below to modify or establish a connection.";
                                status = SSID + status;
                            }
                            else
                            {
                                if (activeNetwork == null)
                                {
                                    status = "WIFI NETWORKS: ";
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(SSID))
                                    {
                                        status = " OBTAINING IP ADDRESS...";
                                        status = SSID + status;
                                    }
                                    else
                                    {
                                        status = "WIFI NETWORKS: ATTEMPTING CONNECTION...";
                                    }
                                }
                            }
                        }
                    }
                }
                IList\\ wifiScanList = wifi.ScanResults;
                    if (wifiScanList != null)
                    {
                        wifis = new string[wifiScanList.Count];
                        for (int i = 0; i \                        {
                            wifis[i] = ((wifiScanList[i]).ToString());
                        }
                        filtered = new List\\();
                        filtered.Add(status);
                        int counter = 0;
                        foreach (string eachWifi in wifis)
                        {
                            var rx = new string[] { "," };
                            string[] temp = eachWifi.Split(rx, StringSplitOptions.None);
                            string lval = temp[0].Substring(5).Trim();
                            if (!string.IsNullOrEmpty(lval) && lval.Length \>\ 3)
                            {
                                filtered.Add(lval);
                                counter++;
                            }
                        }
                    }
                    }
                }
                ListAdapter = new MyListAdapter(this);
            }
            catch (Exception)
            {
            }

            base.OnResume();
        }
Пример #15
0
            private void connectToWifi(string wifiSSID)
            {
                String SSID = "";
                bool connected = false;
                bool hasEverConnected = false;
                int NetworkId = 0;
                try
                {
                    using (Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)context.ApplicationContext.GetSystemService(Context.WifiService))
                    {
                        if (wifi != null && wifi.IsWifiEnabled)
                        {
                            using (WifiInfo wifiInfo = wifi.ConnectionInfo)
                            {
                                if (wifiInfo != null)
                                {
                                    using (NetworkInfo.DetailedState state = WifiInfo.GetDetailedStateOf(wifiInfo.SupplicantState))
                                    {
                                        if (state == NetworkInfo.DetailedState.Connected || state == NetworkInfo.DetailedState.ObtainingIpaddr)
                                        {
                                            SSID = wifiInfo.SSID.Replace("\"", "").Trim();
                                            SSID = SSID.Replace(" ", "");
                                            if (SSID == wifiSSID.Trim().Replace(" ", ""))
                                            {
                                                connected = true;
                                            }
                                        }
                                    }
                                }
                            }

                            IList\\ wifiScanList = wifi.ConfiguredNetworks;
                            for (int i = 0; i \                            {
                                if (((wifiScanList[i]).ToString()).Contains("hasEverConnected: true"))
                                {
                                    String cw = wifiScanList[i].Ssid.Replace("\"", "").Trim();
                                    cw = cw.Replace(" ", "");
                                    if (cw == wifiSSID.Trim().Replace(" ", ""))
                                    {
                                        NetworkId = wifiScanList[i].NetworkId;
                                        hasEverConnected = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                }



                var nxact = new Intent(Application.Context, typeof(ConnectActivity));
                nxact.PutExtra("SSID", wifiSSID);
                nxact.PutExtra("connected", connected);
                nxact.PutExtra("hasEverConnected", hasEverConnected);
                nxact.PutExtra("NetworkId", NetworkId);
                context.StartActivity(nxact);
                activity.Finish();
            }
        /// <summary>
        /// Polls the network state, setting the flags appropriately.
        /// </summary>
        private void PollNetworkState()
        {
            if (this.connectivityManager == null)
            {
                this.connectivityManager = this.GetSystemService(ConnectivityService).JavaCast<ConnectivityManager>();
            }

            if (this.wifiManager == null)
            {
                this.wifiManager = this.GetSystemService(WifiService).JavaCast<WifiManager>();
            }

            if (this.connectivityManager == null)
            {
                Log.Debug(Tag,"LVLDL couldn't get connectivity manager to poll network state");
            }
            else
            {
                NetworkInfo activeInfo = this.connectivityManager.ActiveNetworkInfo;
                this.UpdateNetworkState(activeInfo);
            }
        }
Пример #17
0
 public WifiReceiver(WifiManager manager)
 {
     _wifiManager = manager;
 }
 private static void EnsureNetworkReachable(WifiManager wifiManager, Ssid ssid)
 {
     if (wifiManager.ScanResults.All(x => x.Ssid != ssid.Original))
         throw new InvalidOperationException($"Network {ssid} is unreachable");
 }
Пример #19
0
 public IPAddress GetBroadcastAddress(WifiManager wifi)
 {
     DhcpInfo dhcp;
     try
     {
         dhcp = wifi.DhcpInfo;
     }
     catch (Java.Lang.SecurityException e)
     {
         Debug.WriteLine("Could not obtain Wifi information: {0}. Did you enable ACCESS_WIFI_STATE permission in your app manifest?", e.Message);
         return null;
     }
     var broadcast = (dhcp.IpAddress & dhcp.Netmask) | ~dhcp.Netmask;
     var quads = new byte[4];
     for (var k = 0; k < 4; k++) quads[k] = (byte)((broadcast >> k * 8) & 0xFF);
     return new IPAddress(quads);
 }
Пример #20
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.nconnect);
            Bundle extras = Intent?.Extras;

            if (extras == null)
            {
                Finish();
                return;
            }
            string SSID             = extras.GetString("SSID", "");
            bool   connected        = extras.GetBoolean("connected", false);
            bool   hasEverConnected = extras.GetBoolean("hasEverConnected", false);
            int    NetworkId        = extras.GetInt("NetworkId", 0);

            if (string.IsNullOrEmpty(SSID))
            {
                Finish();
                return;
            }
            Button   ok           = (Button)FindViewById(Resource.Id.okButton);
            Button   forgetButton = (Button)FindViewById(Resource.Id.forgetButton);
            TextView pass         = (TextView)FindViewById(Resource.Id.textviewPassword);

            if (!hasEverConnected)
            {
                forgetButton.Text = "RETURN";
            }
            if (connected)
            {
                ok.Text = "(CONNECTED)";
                ok.SetBackgroundResource(Resource.Color.black);
                ok.Enabled = false;
            }
            if (hasEverConnected || connected)
            {
                pass.Text    = "***********";
                pass.Enabled = false;
            }
            else
            {
                LoadBClicks();
            }
            ok.Click += delegate
            {
                if (hasEverConnected)
                {
                    try
                    {
                        using (Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)ApplicationContext.GetSystemService(Context.WifiService))
                        {
                            if (wifi != null && wifi.IsWifiEnabled)
                            {
                                wifi.Disconnect();
                                wifi.EnableNetwork(NetworkId, true);
                                wifi.Reconnect();
                            }
                        }
                    }
                    catch { }
                }
                else
                {
                    finallyConnect(pass.Text, SSID);
                }
                Finish();
            };

            forgetButton.Click += delegate
            {
                try
                {
                    using (Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)ApplicationContext.GetSystemService(Context.WifiService))
                    {
                        if (wifi != null && wifi.IsWifiEnabled)
                        {
                            if (hasEverConnected)
                            {
                                wifi.RemoveNetwork(NetworkId);
                            }
                        }
                    }
                }
                catch { }
                Finish();
            };
        }
 private static bool IsConnectedToNetwork(WifiManager wifiManager, Ssid ssid)
 {
     return wifiManager.IsWifiEnabled
            && wifiManager.ConnectionInfo != null
            && wifiManager.ConnectionInfo.SSID == ssid.Quoted;
 }
 private static void EnsureWifiEnabled(WifiManager wifiManager)
 {
     if (!wifiManager.IsWifiEnabled)
         throw new InvalidOperationException("Wifi is disabled");
 }
 private static bool IsCompletelyConnected(WifiManager wifiManager, WifiConfiguration network)
 {
     return wifiManager.WifiState == WifiState.Enabled
            && wifiManager.ConnectionInfo.SSID == network.Ssid
            && wifiManager.ConnectionInfo.SupplicantState == SupplicantState.Completed
            && wifiManager.DhcpInfo.IpAddress > 0;
 }
Пример #24
0
		public int ActivateNetwork(int networkCode) {
			if (networkCode == 0) {
				//Turn on mobile data
				return 0;
			} else if (networkCode == 1) {
				wifi = (WifiManager)GetSystemService (WifiService);
				wifi.SetWifiEnabled (true);
				return 1;
			}

			return -1;
		}
 private static void ActivateNetwork(WifiManager wifiManager, WifiConfiguration network)
 {
     if (!wifiManager.EnableNetwork(network.NetworkId, true))
         throw new InvalidOperationException($"Can't enable network {network.Ssid}");
 }
        /// <summary>
        /// OnCreate() detects some of our managers
        /// </summary>
        public override void OnCreate()
        {
            Log.Debug(TAG, "StreamingService.OnCreate()");
            base.OnCreate();

            audioManager = (AudioManager)GetSystemService(AudioService);
            wifiManager = (WifiManager)GetSystemService(WifiService);
            headphonesUnpluggedReceiver = new MusicBroadcastReceiver();
            if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                mediaSession = new MediaSession(this, "KVMRMediaSession");

                mediaCallback = new MediaSessionCallback();
                mediaCallback.OnPlayImpl = () =>
                {
                    if (IsPlaying)
                    {
                        Log.Debug(TAG, "MediaCallback stop playing");
                        Stop();
                        MessagingCenter.Send<PlayerStoppedMessage>(new PlayerStoppedMessage(), "PlayerStopped");
                    }
                    else
                    {
                        Log.Debug(TAG, "MediaCallback start playing. source: " + source ?? "null");
                        Play(source);
                        MessagingCenter.Send(new RemoteControlPlayMessage(), "RemoteControlPlay");
                    }
                };

                mediaSession.SetCallback(mediaCallback);
                mediaSession.SetFlags(MediaSessionFlags.HandlesMediaButtons |
                    MediaSessionFlags.HandlesTransportControls);

                PlaybackState state = new PlaybackState.Builder()
                    .SetActions(PlaybackState.ActionPlay | PlaybackState.ActionPlayPause
                                          | PlaybackState.ActionPause | PlaybackState.ActionStop)
                    .Build();
                mediaSession.SetPlaybackState(state);
                mediaSession.Active = true;
            }
        }
        private static async Task<ConnectionResult> WaitUntilConnectedAsync(WifiManager wifiManager, WifiConfiguration network, TimeSpan checkInterval, TimeSpan timeout)
        {
            // TODO: Get notified when network is active instead of looping and sleeping

            if (timeout != TimeSpan.Zero)
            {
                if (checkInterval == TimeSpan.Zero)
                {
                    if (timeout.TotalMilliseconds > 0)
                        await Task.Delay(timeout);
                }
                else
                {
                    var startTime = DateTime.Now;
                    while (DateTime.Now - startTime < timeout)
                    {
                        if (IsCompletelyConnected(wifiManager, network))
                            return ConnectionResult.Connected;
                        await Task.Delay(TimeSpan.FromMilliseconds(100));
                    }
                }
            }
            if (IsCompletelyConnected(wifiManager, network))
                return ConnectionResult.Connected;
            return ConnectionResult.NotYetConnected;
        }