Exemplo n.º 1
0
		public bool ConnectionStatus(ConnectivityManager type)
		{
			switch (type)
			{
				case ConnectivityManager.TYPE_MOBILE:
					return DeviceNetworkInformation.IsCellularDataEnabled;

				case ConnectivityManager.TYPE_WIFI:
					return DeviceNetworkInformation.IsWiFiEnabled;

				default:
					return false;
			}
		}
Exemplo n.º 2
0
        public static string GetNetworkLevel(this Context context)
        {
            try
            {
                ConnectivityManager connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
                var hasWifi = connectivityManager.GetNetworkInfo(ConnectivityType.Wifi);

                if (hasWifi != null)
                {
                    var wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
                    var wifiInfo    = wifiManager.ConnectionInfo;

                    if (wifiInfo != null)
                    {
                        return(string.Format("Wifi {0} mbps", wifiInfo.LinkSpeed));
                    }
                }

                var hasMobileNetwork = connectivityManager.GetNetworkInfo(ConnectivityType.Mobile);

                if (hasMobileNetwork != null)
                {
                    var telManager = (TelephonyManager)context.GetSystemService(Context.TelephonyService);

                    var networkInfo = telManager.NetworkType;

                    return(string.Format("Mobile network {0}", networkInfo));
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }

            return(string.Empty);
        }
Exemplo n.º 3
0
    void Awake()
    {
        Debug.Log("Inicializando escena INGAME...");
        GameObject go_Connectivity = GameObject.Find("Connectivity_GO");

        if (go_Connectivity == null)
        {
            go_Connectivity = (GameObject)Instantiate(Connectivity_Prefab, Vector3.zero, Quaternion.identity);
            ConnectivityManager.InitializeConnectivity();
        }


        // 3) INICIALIZAR LOS ASSETS DEL IAP
        //IAP_Assets.Initialize();
        // 4) INICIALIZAR EL MANAGER DE CONECTIVIDAD <GameState, Rankings, Logros>
        //ConnectivityManager.InitializeConnectivity();

        // 1) SHOP MANAGER
        ShopManager.CreateManager(); // --> modificar para que pille todos los VirtualGoods y los CurrencyPacks y los meta en listas con todos los datos.

        // 2) INVENTORY MANAGER
        InventoryManager.CreateManager();            // --> mod esto
        InventoryManager.Instance.LoadInGameItems(); // --> mod esto

        // 5) INICIALIZAR MANAGER DE IAP
        //IAPManager.CreateManager();
        // 6)


        GameLogicManager.CreateManager();
        EnvironmentManager.CreateManager();
        //EnvironmentManager.Instance.loadLevel(PlayerPrefs.GetString("stage"));

        //Provisional
        EnvironmentManager.Instance.loadLevel("Beach");
    }
Exemplo n.º 4
0
        public bool CheckInternetConnection()
        {
            bool connected = false;

            connectivityManager = (ConnectivityManager)Xamarin.Forms.Forms.Context.GetSystemService(Context.ConnectivityService);
            networkInfo         = connectivityManager.ActiveNetworkInfo;
            if (networkInfo != null && networkInfo.IsConnectedOrConnecting)
            {
                if (networkInfo.Type == ConnectivityType.Mobile)
                {
                    connected = networkInfo.IsConnected;
                }

                if (networkInfo.Type == ConnectivityType.Wifi)
                {
                    connected = networkInfo.IsConnected;
                }
                else
                {
                    connected = false;
                }
            }
            return(connected);
        }
Exemplo n.º 5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.signupcourses);
            college             = Intent.GetStringExtra("college") ?? "";
            department          = Intent.GetStringExtra("department") ?? "";
            name                = Intent.GetStringExtra("name") ?? "";
            title               = Intent.GetStringExtra("title") ?? "";
            password            = Intent.GetStringExtra("password") ?? "";
            email               = Intent.GetStringExtra("email") ?? "";
            staffid             = Intent.GetStringExtra("staffid") ?? "";
            name                = Intent.GetStringExtra("name") ?? "";
            collss              = "\"" + college + "\"";
            depss               = "\"" + department + "\"";
            auth                = FirebaseAuth.Instance;
            connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
            courseListView      = FindViewById <ListView>(Resource.Id.courseList);
            searchcourse        = FindViewById <EditText>(Resource.Id.coursesSearch);
            courseWelcmMsg      = FindViewById <TextView>(Resource.Id.courseWelcome);
            prevButt            = FindViewById <TextView>(Resource.Id.coursesPrevious);
            nextButt            = FindViewById <TextView>(Resource.Id.coursesNext);
            signupCoursespgb    = FindViewById <ProgressBar>(Resource.Id.signupCoursespgb);
            signupCoursesHolder = FindViewById <LinearLayout>(Resource.Id.signupCoursesHolder);
            searchcourse.ClearFocus();
            db       = new DbHelper(this);
            sqliteDB = db.WritableDatabase;
            AddData();
            ArrayAdapter <string> corseadapt = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItemMultipleChoice, courselist);

            courseListView.ChoiceMode          = ChoiceMode.Multiple;
            courseListView.Adapter             = corseadapt;
            courseListView.OnItemClickListener = this;
            prevButt.SetOnClickListener(this);
            nextButt.SetOnClickListener(this);
            courseWelcmMsg.Text = "Thank You " + name + "! This is the last stage";
        }
Exemplo n.º 6
0
 public Connectivity(Context context)
 {
     _context  = context;
     _cManager = (ConnectivityManager)_context.GetSystemService(Context.ConnectivityService);
 }
Exemplo n.º 7
0
        public void Initialize()
        {
            // A Licensing and In-App Billing public key is required before an app can communicate with
            // Google Play, however you DON'T want to store the key in plain text with the application.
            // The Unify command provides a simply way to obfuscate the key by breaking it into two or
            // or more parts, specifying the order to reassemlbe those parts and optionally providing
            // a set of key/value pairs to replace in the final string.
            string value = Security.Unify(
                new string[] {
                "Insert part 0",
                "Insert part 3",
                "Insert part 2",
                "Insert part 1"
            },
                new int[] { 0, 3, 2, 1 });

            // Create a new connection to the Google Play Service
            _serviceConnection              = new InAppBillingServiceConnection(MainActivity.Instance, value);
            _serviceConnection.OnConnected += () =>
            {
                this._serviceConnection.BillingHandler.OnProductPurchased += (int response, Purchase purchase, string purchaseData, string purchaseSignature) =>
                {
                    // Record what we purchased
                    var epoch        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    var purchaseTime = epoch.AddMilliseconds(purchase.PurchaseTime);
                    var newPurchase  = new InAppPurchase
                    {
                        OrderId      = purchase.OrderId,
                        ProductId    = purchase.ProductId,
                        PurchaseTime = purchaseTime
                    };
                    App.ViewModel.Purchases.Add(newPurchase);

                    // Let anyone know who is interested that purchase has completed
                    if (this.OnPurchaseProduct != null)
                    {
                        this.OnPurchaseProduct();
                    }
                };
                this._serviceConnection.BillingHandler.QueryInventoryError += (int responseCode, Bundle skuDetails) =>
                {
                    if (this.OnQueryInventoryError != null)
                    {
                        this.OnQueryInventoryError(responseCode, null);
                    }
                };
                this._serviceConnection.BillingHandler.BuyProductError += (int responseCode, string sku) =>
                {
                    // Note, BillingResult.ItemAlreadyOwned, etc. can be used to determine error

                    if (this.OnPurchaseProductError != null)
                    {
                        this.OnPurchaseProductError(responseCode, sku);
                    }
                };
                this._serviceConnection.BillingHandler.InAppBillingProcesingError += (string message) =>
                {
                    if (this.OnInAppBillingProcesingError != null)
                    {
                        this.OnInAppBillingProcesingError(message);
                    }
                };
                this._serviceConnection.BillingHandler.OnInvalidOwnedItemsBundleReturned += (Bundle ownedItems) =>
                {
                    if (this.OnInvalidOwnedItemsBundleReturned != null)
                    {
                        this.OnInvalidOwnedItemsBundleReturned(null);
                    }
                };
                this._serviceConnection.BillingHandler.OnProductPurchasedError += (int responseCode, string sku) =>
                {
                    if (this.OnPurchaseProductError != null)
                    {
                        this.OnPurchaseProductError(responseCode, sku);
                    }
                };
                this._serviceConnection.BillingHandler.OnPurchaseFailedValidation += (Purchase purchase, string purchaseData, string purchaseSignature) =>
                {
                    if (this.OnPurchaseFailedValidation != null)
                    {
                        this.OnPurchaseFailedValidation(null, purchaseData, purchaseSignature);
                    }
                };
                this._serviceConnection.BillingHandler.OnUserCanceled += () =>
                {
                    if (this.OnUserCanceled != null)
                    {
                        this.OnUserCanceled();
                    }
                };

                this._connected = true;

                // Load inventory or available products
                this.QueryInventory();
            };

            /* Uncomment these if you want to be notified for these events
             * _serviceConnection.OnDisconnected += () =>
             * {
             *  System.Diagnostics.Debug.WriteLine("Remove");
             * };
             *
             * _serviceConnection.OnInAppBillingError += (error, message) =>
             *  {
             *      System.Diagnostics.Debug.WriteLine("Remove");
             *  };
             */

            // Are we connected to a network?
            ConnectivityManager connectivityManager = (ConnectivityManager)MainActivity.Instance.GetSystemService(MainActivity.ConnectivityService);
            NetworkInfo         activeConnection    = connectivityManager.ActiveNetworkInfo;

            if ((activeConnection != null) && activeConnection.IsConnected)
            {
                // Ok, carefully attempt to connect to the in-app service
                try
                {
                    _serviceConnection.Connect();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception trying to connect to in app service: " + ex);
                }
            }
        }
Exemplo n.º 8
0
 public cSocial()
 {
     Debug.Log(ConnectivityManager.SocialAuthenticate() ? "Connected" : "Disconnected");
 }
Exemplo n.º 9
0
    public void drawKappaItemsTest()
    {
        GUILayout.BeginArea(new Rect(10, 200, 200, 250));
        GUILayout.BeginVertical("box");
        GUILayout.Label("Showing Items TESTING");

        if (GUILayout.Button("Fill cloud Data"))
        {
            ConnectivityManager.FillGameState();
            aux_byteArray = ConnectivityManager.SerializeGameState(ConnectivityManager.ECloudGameState);
        }

        if (GUILayout.Button("Deserialize cloud Data"))
        {
            gameState = ConnectivityManager.DeserializeGameStateByteArray(aux_byteArray);
            addDebugMessage("total_mangos: " + gameState.total_mangos);
            addDebugMessage("total_meters: " + gameState.total_meters);
            addDebugMessage("total_frogs: " + gameState.total_frogs);
            addDebugMessage("total_cocktails: " + gameState.total_cocktails);
            addDebugMessage("object[1]: " + gameState.list_CloudItems[1].local_id);

            /*
             * List<cUI_Item> aux = ShopManager.Instance.UI_List_All_Items;
             * for (int i = 0; i < aux.Count; ++i)
             * {
             *  Debug.Log("Loaded item: " + aux[i].name);
             * }*/
        }

        if (GUILayout.Button("Save Game2Cloud"))
        {
            ConnectivityManager.SaveCurrentGameState();
        }

        /*
         * if (GUILayout.Button("Show surfboard"))
         * {
         *  InventoryManager.Instance.setKappaItemVisibleByName("prop_surfboard", true);
         * }
         * GUILayout.Space(5);
         *
         * if (GUILayout.Button("Hide surfboard"))
         * {
         *  InventoryManager.Instance.setKappaItemVisibleByName("prop_surfboard", false);
         * }
         *
         * if (GUILayout.Button("Enable visualSet"))
         * {
         *  GameLogicManager.Instance.EnableKappaVisualData();
         * }
         *
         * if (GUILayout.Button("Disable visualSet"))
         * {
         *  GameLogicManager.Instance.DisableKappaVisualData();
         * }
         *
         * if (GUILayout.Button("List items"))
         * {
         *  List<cUI_Item> aux = ShopManager.Instance.UI_List_All_Items;
         *  for (int i = 0; i < aux.Count; ++i)
         *  {
         *      Debug.Log("Loaded item: " + aux[i].name);
         *  }
         * } */

        GUILayout.Space(5);
        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
Exemplo n.º 10
0
        private async void GetMyFriends()
        {
            var traveler = JsonConvert.DeserializeObject <Traveler>(preferences.GetString("traveler", null));

            connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
            activeNetworkInfo   = connectivityManager.ActiveNetworkInfo;
            if (traveler == null || token == null)
            {
                Toast.MakeText(this, GetString(Resource.String.LoginTokenOrTravelerFailure), ToastLength.Long).Show();
                Finish();
                StartActivity(typeof(LoginActivity));
            }
            else if (activeNetworkInfo == null || !activeNetworkInfo.IsConnected)
            {
                Toast.MakeText(this, GetString(Resource.String.NoConnectionInfo), ToastLength.Long).Show();
            }
            else
            {
                var url = string.Format(GetString(Resource.String.ApiLink)
                                        + "/api/friendlist/getfriendlist?ownerId={0}", traveler.Id);
                client = new HttpClient();
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue(token.TokenType, token.AccessToken);

                var loadingMessage = ProgressDialog.Show(this, GetString(Resource.String.LoadingFriendListTitle),
                                                         GetString(Resource.String.LoadingFriendListContent), true, false);
                var response = await client.GetAsync(new Uri(url));

                loadingMessage.Dismiss();

                mItems.Clear();
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    var friendListItems = JsonConvert.DeserializeObject <List <FriendListItem> >(content);
                    foreach (var friendListItem in friendListItems)
                    {
                        mItems.Add(new FriendListItem
                        {
                            Id       = friendListItem.Id,
                            OwnerId  = friendListItem.OwnerId,
                            FriendId = friendListItem.FriendId,
                            Owner    = friendListItem.Owner,
                            Friend   = friendListItem.Friend
                        });
                    }
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    Toast.MakeText(this, GetString(Resource.String.LoadingFriendListEmptyInfo), ToastLength.Long).Show();
                }
                else
                {
                    Toast.MakeText(this, GetString(Resource.String.LoadingFriendListNotOkInfo), ToastLength.Long).Show();
                }

                var adapter = new MyFriendsListViewAdapter(this, mItems);
                mMyFriendsList.Adapter = adapter;
            }
        }
Exemplo n.º 11
0
        /*
         * protected override void OnResume()
         * {
         *  base.OnResume();
         *
         *  Toast.MakeText(this, "OnResumeLoading", ToastLength.Short).Show();
         * }
         */

        protected override void OnCreate(Bundle savedInstanceState)
        {
            MobileCenter.Start("005f8f23-ea2c-48ac-962f-b4929664c618",
                               typeof(Analytics), typeof(Crashes));

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.anim_layout);

            var restartBn = FindViewById <Button>(Resource.Id.restartBN);

            //using plugin when it is the first app launch
            CrossVersionTracking.Current.Track();
            var vt = CrossVersionTracking.Current;

            vt.OnFirstLaunchOfVersion("1.0", () => firstMethod());
            //using plugin when it is the first app launch ended

            //checking internet connection
            ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);

            NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
            bool        isOnline         = (activeConnection != null) && activeConnection.IsConnected;

            //checking internet connection ended

            if (isOnline == true)
            {
                restartBn.Visibility = ViewStates.Gone;

                /*_x = MAIN_Activity._x;
                *  _y = MAIN_Activity._y;*/
                //Create the DB:
                DB.myDBRepo dbr = new DB.myDBRepo();
                dbr.CreateDB();
                //Create table:
                dbr.CreateTable();
                dbr.CreateTableC_F();
                dbr.CreateIndicatorTable();
                dbr.CreateCoordsTable();

                //setting celsiusOr_fahrenheit by default
                if (dbr.GetAllRecordsC_F() == "celsius")
                {
                    SettingsActivity.c_f_Global = "celsius";
                }
                else
                {
                    SettingsActivity.c_f_Global = "fahrenheit";
                }
                //setting celsiusOr_fahrenheit by default ended

                if (MAIN_Activity.firstAppLaunchGlob == false && MAIN_Activity.ipressedGlob == false)
                {
                    dbr.GetAllRecords();
                }

                Animation myAnimation = AnimationUtils.LoadAnimation(this, Resource.Animation.MyAnimation);
                ImageView myImage     = FindViewById <ImageView>(Resource.Id.imageView1);

                myImage.StartAnimation(myAnimation);
                dbr.CreateIndicatorTable();

                string dbPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "MyDB.db3");
                var    db     = new SQLiteConnection(dbPath);
                var    cityOrCoordIndicator = db.Table <DB.cityOrCoordIndicator>();

                MainActivity ma = new MainActivity();

                ma.city_or_coord();

                if (MAIN_Activity.cityButtonPressedIndicGlob == false)
                {
                    var coordinates = db.Table <DB.coordinates>();
                    foreach (var b in coordinates)
                    {
                        _x = b._X;
                        _y = b._Y;
                    }
                }
                if (MAIN_Activity.firstAppLaunchGlob == false)
                {
                    Displaying();
                }

                ISharedPreferences       pref = Application.Context.GetSharedPreferences("WeatherData", FileCreationMode.Private);
                ISharedPreferencesEditor edit = pref.Edit();
                if (MAIN_Activity._addressTextGlobalVariable != null)
                {
                    edit.PutString("addressTextGlobalVariable", MAIN_Activity._addressTextGlobalVariable);
                }
                if (MAIN_Activity._locationTextGlobalVariable != null)
                {
                    edit.PutString("locationTextGlobalVariable", MAIN_Activity._locationTextGlobalVariable);
                }
                edit.Apply();
            }
            else
            {
                if (MAIN_Activity.firstAppLaunchGlob == false)
                {
                    Toast.MakeText(this, "No Internet Connection.\nTurn the Internet connection on and click \"Restart\"", ToastLength.Long).Show();
                }
                //fonts
                Typeface tf = Typeface.CreateFromAsset(Assets, "dosis.book.ttf");
                restartBn.SetTypeface(tf, TypefaceStyle.Bold);
                //fonts ended
                restartBn.Visibility = ViewStates.Visible;
                restartBn.Click     += RestartBn_Click;
            }
            deleteIncorrectCity();
            FindViewById <Button>(Resource.Id.closeBN).Click += LoadingActivity_Click;
            FindViewById <Button>(Resource.Id.editBN).Click  += LoadingActivity_Click1;
        }
Exemplo n.º 12
0
        public override void OnReceive(Context context, Intent intent)
        {
            try
            {
                Wifi     = (WifiManager)context.GetSystemService(Context.WifiService);
                CManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);

                if (!Wifi.IsWifiEnabled)
                {
                    Wifi.SetWifiEnabled(true);

                    MainActivity.MakeText("WIFI IS OFF", true);
                }

                if (string.IsNullOrWhiteSpace(ConnectedSSID) || ConnectedSSID == "<unknown ssid>")
                {
                    MainActivity.MakeText("WIFI NOT CONNECTED", true);

                    var networkInfo = CManager.ActiveNetworkInfo;

                    if (networkInfo == null || !networkInfo.IsConnectedOrConnecting)
                    {
                        var prefs = context.GetSharedPreferences("Wifiautoconnect", FileCreationMode.Private);

                        var ssid = prefs.GetString("network", "");
                        var pass = prefs.GetString("password", "");

                        if (ssid.Trim().Length > 0)
                        {
                            var NetworkConfig = Wifi.ConfiguredNetworks.Where(n => n.Ssid != null && (n.Ssid == ssid || n.Ssid == "\"" + ssid + "\"")).FirstOrDefault();

                            if (NetworkConfig == null)
                            {
                                NetworkConfig = new WifiConfiguration()
                                {
                                    Ssid         = "\"" + ssid + "\"",
                                    StatusField  = WifiStatus.Enabled,
                                    Priority     = Wifi.ConfiguredNetworks.Max(n => n.Priority) + 1,
                                    PreSharedKey = "\"" + pass + "\""
                                };
                                NetworkConfig.AllowedKeyManagement.Set((int)KeyManagementType.WpaPsk);
                                NetworkConfig.NetworkId = Wifi.AddNetwork(NetworkConfig);

                                Wifi.SaveConfiguration();
                            }

                            if (Wifi.EnableNetwork(NetworkConfig.NetworkId, true))
                            {
                                MainActivity.MakeText("WIFI CONNECTED", true);
                            }
                        }
                    }
                }
                else
                {
                    MainActivity.MakeText("CON SSID: " + ConnectedSSID, false);
                }
            }
            catch (Exception ex)
            {
                MainActivity.MakeText("ERROR WIFI: " + ex.Message + " " + (ex.StackTrace ?? ""), false);
            }
        }
Exemplo n.º 13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            AppCenter.Start("b17f9c9d-e90c-488f-8c4b-92ef3e305c0d", typeof(Analytics), typeof(Distribute));

            var versionInfo = Application.Context.ApplicationContext?.PackageManager?.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0);

            //var username = System.Security.Principal.WindowsIdentity.GetCurrent();

            SentryXamarin.Init(o =>
            {
                o.AddXamarinFormsIntegration();
                o.Dsn         = "https://[email protected]/5390642";
                o.Release     = $"TacControl@{versionInfo?.VersionName}:{versionInfo?.LongVersionCode}";
                o.Environment = //username == "Dedmen-PC\\dedmen" ? "Dev" :
                                "Alpha";
            });


            WifiManager wifiMgr = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService);

            wifiLock = wifiMgr.CreateWifiLock(WifiMode.Full, "TacControl-udp");
            wifiLock.SetReferenceCounted(true);
            wifiLock.Acquire();
            castLock = wifiMgr.CreateMulticastLock("TacControl-udp");
            castLock.SetReferenceCounted(true);
            castLock.Acquire();


            ConnectivityManager conMgr = (ConnectivityManager)ApplicationContext.GetSystemService(Context.ConnectivityService);
            var stuff   = conMgr.GetAllNetworks();
            var wifiNet = stuff.FirstOrDefault(x => conMgr.GetNetworkInfo(x).Type == ConnectivityType.Wifi);

            if (wifiNet != null)
            {
                var res  = conMgr.BindProcessToNetwork(wifiNet);
                var info = conMgr.GetNetworkInfo(wifiNet);

                var connInfo = wifiMgr.ConnectionInfo;
            }


            //Networking.ConnectionInfo

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            Android.Views.Window window = Window;
            window.AddFlags(WindowManagerFlags.KeepScreenOn);
            window.AddFlags(WindowManagerFlags.Fullscreen);

            LoadApplication(new App((action) =>
            {
                TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();
                bool isMain = MainThread.IsMainThread;

                RunOnUiThread(() =>
                {
                    try
                    {
                        action();
                        tcs.SetResult(null);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                });

                return(tcs.Task);
            }));
        }
        /// <inheritdoc/>
        public bool IsInternetCostFree()
        {
            ConnectivityManager connectivity = GetConnectivityManager();

            return(!connectivity.IsActiveNetworkMetered);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Constructor
 /// </summary>
 public NetworkController()
 {
     wifiManager         = (WifiManager)Application.Context.GetSystemService(Android.Content.Context.WifiService);
     connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Android.Content.Context.ConnectivityService);
     wifiLock            = wifiManager.CreateWifiLock(WifiMode.Full, "Wifi lock");
 }
Exemplo n.º 16
0
 public AndroidWlanBroadcastReceiver()
 {
     _connectivityManager = Application.Context.GetSystemService(global::Android.Content.Context.ConnectivityService) as ConnectivityManager;
 }
Exemplo n.º 17
0
 public ReachableDroid()
 {
     connectivityManager = Android.App.Application.Context.GetSystemService(Android.App.Activity.ConnectivityService) as ConnectivityManager;
 }
Exemplo n.º 18
0
        public bool IsNetworkConnected()
        {
            ConnectivityManager cSvc = (ConnectivityManager)ctx.GetSystemService(Context.ConnectivityService);

            return(cSvc.ActiveNetworkInfo != null && cSvc.ActiveNetworkInfo.IsConnected);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:Ipheidi.Droid.NetworkManager"/> class.
 /// </summary>
 public NetworkManager()
 {
     listeners           = new List <INetworkStateListener>();
     connectivityManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.ConnectivityService);
     ListenToNetworkState();
 }
Exemplo n.º 20
0
 public NetworkService()
 {
     this.connectivityManager = (ConnectivityManager)Forms.Context.GetSystemService(Application.ConnectivityService);
 }
Exemplo n.º 21
0
        public void Open(UsbManager usbManager, int bufferSize = DEFAULT_BUFFERSIZE)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            if (IsOpen)
            {
                throw new InvalidOperationException();
            }

            var connection = usbManager.OpenDevice(port.Driver.Device);

            if (connection == null)
            {
                throw new Java.IO.IOException("Failed to open device");
            }
            isOpen = true;

            buffer = new byte[bufferSize];
            port.Open(connection);
            port.SetParameters(BaudRate, DataBits, StopBits, Parity);

            cancelationTokenSource = new CancellationTokenSource();
            var cancelationToken = cancelationTokenSource.Token;

            cancelationToken.Register(() => Log.Info(TAG, "Cancellation Requested"));

            Task.Run(() => {
                Log.Info(TAG, "Task Started!");
                try {
                    while (holdWhile)
                    {
                        Thread.Sleep(7000); //new line
                        cancelationToken.ThrowIfCancellationRequested();
                        sending();          //sending data (new line)
                        Step();             // execute comming data
                        /////////////////////////new line/////////////////////////////////////////
                        ConnectivityManager ConnectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
                        NetworkInfo conn = ConnectivityManager.ActiveNetworkInfo;
                        if (conn == null || !conn.IsConnected)
                        {
                            holdWhile = false;
                        }
                        //////////////////////////////////////////////////////////////////////////////
                    }
                }
                catch (OperationCanceledException) {
                    throw;
                }
                catch (Exception e) {
                    Log.Warn(TAG, "Task ending due to exception: " + e.Message, e);
                    ErrorReceived.Raise(this, new UnhandledExceptionEventArgs(e, false));
                } finally {
                    port.Close();
                    buffer = null;
                    isOpen = false;
                    Log.Info(TAG, "Task Ended!");
                }
            }, cancelationToken);
        }
Exemplo n.º 22
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            this.SetContentView(Resource.Layout.StepOne);

            TextView    txtInternetCheck = FindViewById <TextView>(Resource.Id.txtInternetCheck);
            TextView    wifiName         = FindViewById <TextView>(Resource.Id.wifiName);
            EditText    wifiPass         = FindViewById <EditText>(Resource.Id.wifiPass);
            ListView    wifiNetworkList  = FindViewById <ListView>(Resource.Id.listView1);
            Button      connBtn          = FindViewById <Button>(Resource.Id.wifiConnBtn);
            Button      stepTwoBtn       = FindViewById <Button>(Resource.Id.stepTwoBtn);
            WifiManager wifiManager      = (WifiManager)Application.Context.GetSystemService(WifiService);

            ArrayList networks = new ArrayList();

            if (wifiManager.StartScan())
            {
                foreach (ScanResult network in wifiManager.ScanResults)
                {
                    networks.Add(network.Ssid);
                }
            }


            //connBtn.Visibility = Android.Views.ViewStates.Invisible;
            stepTwoBtn.Visibility = Android.Views.ViewStates.Invisible;

            //Turn on wifi if not enabled
            if (!wifiManager.IsWifiEnabled)
            {
                wifiManager.SetWifiEnabled(true);
            }



            //Supplies wifi connections picked up
            var adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, networks);

            wifiNetworkList.Adapter = adapter;

            //When network name gets clicked
            wifiNetworkList.ItemClick += WifiItemClicked;

            //Gets SSID of item clicked
            void WifiItemClicked(object sender, AdapterView.ItemClickEventArgs e)
            {
                string selectedItem = (string)networks[e.Position];

                wifiName.Visibility = Android.Views.ViewStates.Visible;
                wifiPass.Visibility = Android.Views.ViewStates.Visible;
                connBtn.Visibility  = Android.Views.ViewStates.Visible;
                wifiName.Text       = selectedItem;
                wifiPass.Hint       = $"Enter password for {selectedItem}";
            }

            //Connect to the wifi
            connBtn.Click += delegate {
                InputMethodManager inputManager = (InputMethodManager)this.GetSystemService(Context.InputMethodService);
                inputManager.HideSoftInputFromWindow(this.CurrentFocus.WindowToken, HideSoftInputFlags.NotAlways);

                var wifiConfig = new WifiConfiguration();
                wifiConfig.Ssid         = string.Format("\"{0}\"", wifiName.Text);
                wifiConfig.PreSharedKey = string.Format("\"{0}\"", wifiPass.Text);

                using (WifiManager wifiManager2 = (WifiManager)Application.Context.GetSystemService(Context.WifiService))
                {
                    int netId = wifiManager2.AddNetwork(wifiConfig);
                    wifiManager2.Disconnect();
                    wifiManager2.EnableNetwork(netId, true);
                    wifiManager2.Reconnect();
                }

                txtInternetCheck.Text = "Connecting...Please Wait";

                //Thread.Sleep(7000);

                //ConnectivityManager connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
                //var netInfo = connectivityManager.ActiveNetworkInfo;

                ////netInfo.IsConnected &&
                //if (netInfo.Type == ConnectivityType.Wifi)
                //{
                //    txtInternetCheck.Text = "Great, you are connected!";
                //    stepTwoBtn.Visibility = Android.Views.ViewStates.Visible;
                //}
                //else
                //{
                //    txtInternetCheck.Text = "Something went wrong. Please try again.";
                //}


                Thread thread = new Thread(() =>
                {
                    Thread.Sleep(7000);

                    ConnectivityManager connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
                    var netInfo = connectivityManager.ActiveNetworkInfo;

                    //netInfo.IsConnected &&
                    if (netInfo.Type == ConnectivityType.Wifi)
                    {
                        RunOnUiThread(() =>
                        {
                            txtInternetCheck.Text = "Great, you are connected!";
                            stepTwoBtn.Visibility = Android.Views.ViewStates.Visible;
                        });
                    }
                    else if (netInfo == null)
                    {
                        RunOnUiThread(() =>
                        {
                            txtInternetCheck.Text = "Something went wrong. Please try again.";
                        });
                    }
                });
                thread.Start();
            };

            stepTwoBtn.Click += delegate {
                Intent intent = new Intent(this, typeof(ActivateActivity));
                StartActivity(intent);
                Finish();
            };
        }
Exemplo n.º 23
0
        private bool isOnline()
        {
            ConnectivityManager cm = (ConnectivityManager)this.Activity.GetSystemService(Context.ConnectivityService);

            return(cm.ActiveNetworkInfo != null && cm.ActiveNetworkInfo.IsConnected);
        }
Exemplo n.º 24
0
    public void drawSocialTest()
    {
        if (!achievement_testing)
        {
            return;
        }

        GUILayout.BeginArea(new Rect(Screen.width - 210, 10, 200, Screen.height));
        GUILayout.BeginVertical("box");
        GUILayout.Label("Achievement system TESTING");
        GUILayout.Space(10);

        if (GUILayout.Button("Log in"))
        {
            if (ConnectivityManager.SocialAuthenticate())
            {
                logged_state = true;
            }
        }
        GUILayout.Space(5);

        if (GUILayout.Button("First achievement"))
        {
            if (ConnectivityManager.ReportAchievement(Achievements_Android.ACHIEVEMENT_ONE, 100))
            {
                first_achievement_state = true;
            }
        }
        GUILayout.Space(5);

        if (GUILayout.Button(incremental_counter + " times for Inc.achievement!"))
        {
            if (ConnectivityManager.ReportIncrementalAchievement(Achievements_Android.ACHIEVEMENT_TWO_INCREMENTAL, 5))
            {
                --incremental_counter;
            }
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Third achievement"))
        {
            if (ConnectivityManager.ReportAchievement(Achievements_Android.ACHIEVEMENT_THREE, 100))
            {
                //first_achievement_state = true;
            }
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Fourth achievement"))
        {
            if (ConnectivityManager.ReportAchievement(Achievements_Android.ACHIEVEMENT_FOUR, 100))
            {
                //first_achievement_state = true;
            }
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Fifth achievement"))
        {
            if (ConnectivityManager.ReportAchievement(Achievements_Android.ACHIEVEMENT_FIVE, 100))
            {
                //first_achievement_state = true;
            }
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Post 1000 points to LB"))
        {
            ConnectivityManager.ReportScore(1000, Achievements_Android.SCORE_BLACKBOARD);
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Show Achievements"))
        {
            ConnectivityManager.ShowAchievements();
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Show Scores"))
        {
            ConnectivityManager.ShowLeaderBoard();
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Get coins from DB"))
        {
            ConnectivityManager.SocialAuthenticate();
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Add 30 coins"))
        {
            ConnectivityManager.SocialAuthenticate();
        }
        GUILayout.Space(5);


        if (GUILayout.Button("Add 50 coins"))
        {
            ConnectivityManager.SocialAuthenticate();
        }
        GUILayout.Space(5);

        if (GUILayout.Button("Logout"))
        {
            ConnectivityManager.SocialAuthenticate();
        }

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
Exemplo n.º 25
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();
        }
Exemplo n.º 26
0
 public NetworkHelper(Context context, string host = "http://www.bing.com")
 {
     this._context        = context;
     HostName             = host;
     _connectivityManager = (ConnectivityManager)_context.GetSystemService(Context.ConnectivityService);
 }
Exemplo n.º 27
0
        /**
         * Get the network info
         * @param context
         * @return
         */
        public static NetworkInfo GetNetworkInfo(Context context)
        {
            ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);

            return(cm.ActiveNetworkInfo);
        }
Exemplo n.º 28
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            receiver = new NetworkBroadcastReceiver(this);
            receiver.SetListener(this);
            intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
            RegisterReceiver(receiver, intentFilter);

            tvNetworkNotification = (TextView)FindViewById(Resource.Id.network_notification);
            ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);

            if (cm.ActiveNetworkInfo == null)
            {
                var ad = new Android.Support.V7.App.AlertDialog.Builder(this);
                ad.SetTitle("No Connection");
                ad.SetMessage("Looks like there's a problem with your network connection. Try again later.");
                ad.SetCancelable(false);
                ad.SetPositiveButton("OK", this);
                Android.Support.V7.App.AlertDialog dialog = ad.Create();
                dialog.Show();
            }
            else
            {
                MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.googlemap);
                mapFragment.GetMapAsync(this);

                toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);
                SetSupportActionBar(toolbar);

                // Deserialize the member object
                ISharedPreferences pref = GetSharedPreferences(GetString(Resource.String.PreferenceFileName), FileCreationMode.Private);
                var member = pref.GetString(GetString(Resource.String.PreferenceSavedMember), "");
                user = JsonConvert.DeserializeObject <Member>(member);

                var profile = new ProfileDrawerItem();
                profile.WithName(user.username);
                profile.WithIdentifier(100);

                headerResult = new AccountHeaderBuilder()
                               .WithActivity(this)
                               .WithHeaderBackground(Resource.Drawable.profilebackground)
                               .WithSelectionListEnabledForSingleProfile(false)
                               .AddProfiles(profile)
                               .WithOnAccountHeaderListener(this)
                               .WithSavedInstance(bundle)
                               .Build();

                var header = new PrimaryDrawerItem();
                header.WithName(Resource.String.Drawer_Item_Trips);
                header.WithIcon(GoogleMaterial.Icon.GmdDirectionsCar);
                header.WithIdentifier(1);

                var logoutDrawer = new SecondaryDrawerItem();
                logoutDrawer.WithName(Resource.String.Drawer_Item_Logout);
                logoutDrawer.WithIcon(GoogleMaterial.Icon.GmdSettingsPower);
                logoutDrawer.WithIdentifier(4);

                //create the drawer and remember the `Drawer` result object
                Drawer result = new DrawerBuilder()
                                .WithActivity(this)
                                .WithToolbar(toolbar)
                                .WithAccountHeader(headerResult)
                                .AddDrawerItems(
                    header,
                    new DividerDrawerItem(),
                    logoutDrawer
                    )
                                .WithOnDrawerItemClickListener(this)
                                .Build();

                originAutocompleteFragment = (PlaceAutocompleteFragment)
                                             FragmentManager.FindFragmentById(Resource.Id.place_autocomplete_origin_fragment);
                originAutocompleteFragment.SetHint("Enter the origin");
                originAutocompleteFragment.PlaceSelected += OnOriginSelected;

                destAutocompleteFragment = (PlaceAutocompleteFragment)
                                           FragmentManager.FindFragmentById(Resource.Id.place_autocomplete_destination_fragment);
                destAutocompleteFragment.SetHint("Enter the destination");
                destAutocompleteFragment.PlaceSelected += OnDestinationSelected;

                progress = new ProgressDialog(this);
                progress.Indeterminate = true;
                progress.SetProgressStyle(ProgressDialogStyle.Spinner);
                progress.SetMessage("Getting location...");
                progress.SetCancelable(false);
                RunOnUiThread(() =>
                {
                    progress.Show();
                });

                // Request Update request
                locationManager = (LocationManager)GetSystemService(Context.LocationService);
                IList <string> providers    = locationManager.AllProviders;
                Criteria       criteria     = new Criteria();
                string         bestProvider = locationManager.GetBestProvider(criteria, true);
                locationManager.RequestLocationUpdates(bestProvider, MIN_TIME, MIN_DISTANCE, this);
            }
        }
 public ConnectivityMonitor(BaseApplication <U> app)
 {
     this.app                   = app;
     connectivityManager        = (ConnectivityManager)app.GetSystemService(Context.ConnectivityService);
     networkStateChangeReceiver = new NetworkStateChangeReceiver(this);
 }
 public WifiAndroidConnectCallback(ConnectivityManager manager, string host, int port)
 {
     this.connectivityManager = manager;
     this.host = host;
     this.port = port;
 }
Exemplo n.º 31
0
 public ConnectivityImpl()
 {
     this.wifiManager         = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
     this.telManager          = (TelephonyManager)Application.Context.ApplicationContext.GetSystemService(Context.TelephonyService);
     this.connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
 }