Beispiel #1
0
 public override void OnReceive(Context context, Intent intent)
 {
     var str1 = intent.GetStringExtra ("team1");
     var str2 = intent.GetStringExtra ("team2");
     var count1 = intent.GetStringExtra ("count");
     var iconId = intent.GetStringExtra ("icon");
     Console.WriteLine ("Servise Start");
     PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
     PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Partial, "NotificationReceiver");
     w1.Acquire ();
     Notification.Builder builder = new Notification.Builder (context)
         .SetContentTitle (context.Resources.GetString(Resource.String.matchIsStarting))
         .SetContentText (str1+" VS. "+str2)
         .SetSmallIcon (Convert.ToInt32(iconId));
     // Build the notification:
     Notification notification = builder.Build();
     notification.Defaults = NotificationDefaults.All;
     // Get the notification manager:
     NotificationManager notificationManager = (NotificationManager)context.GetSystemService (Context.NotificationService);
     // Publish the notification:
     int notificationId = Convert.ToInt32(count1);
     notificationManager.Notify (notificationId, notification);
     w1.Release ();
     var tempd = DateTime.UtcNow;
     Console.WriteLine ("Alarm: " + tempd);
 }
Beispiel #2
0
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, "NotificationReceiver");
            w1.Acquire ();

            //Toast.MakeText (context, "Received intent!", ToastLength.Short).Show ();
            var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService);
            //var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            //Clicking the pending intent does not go to the Home Activity Screen, but to the last activity that was active before leaving the app
            var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(Home)), PendingIntentFlags.UpdateCurrent);
            //Notification should be language specific
            notification.SetLatestEventInfo (context, context.Resources.GetString(Resource.String.ReminderTitle), context.Resources.GetString(Resource.String.InvalidationText), pendingIntent);
            notification.Flags |= NotificationFlags.AutoCancel;
            nMgr.Notify (0, notification);

            //			Vibrator vibrator = (Vibrator) context.GetSystemService(Context.VibratorService);
            //			if (vibrator != null)
            //				vibrator.Vibrate(400);

            //change shared preferences such that the questionnaire button can change its availability
            ISharedPreferences sharedPref = context.GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private);
            ISharedPreferencesEditor editor = sharedPref.Edit();
            editor.PutBoolean("QuestionnaireActive", false );
            editor.Commit ();

            //insert a line of -1 into some DB values to indicate that the questions have not been answered at the scheduled time
            MoodDatabase dbMood = new MoodDatabase(context);
            ContentValues insertValues = new ContentValues();
            insertValues.Put("date", DateTime.Now.ToString("dd.MM.yy"));
            insertValues.Put("time", DateTime.Now.ToString("HH:mm"));
            insertValues.Put("mood", -1);
            insertValues.Put("people", -1);
            insertValues.Put("what", -1);
            insertValues.Put("location", -1);
            //use the old value of questionFlags
            Android.Database.ICursor cursor;
            cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, QuestionFlags FROM MoodData WHERE date = '" + DateTime.Now.ToString("dd.MM.yy") + "'", null); // cursor query
            int alreadyAsked = 0; //default value: no questions have been asked yet
            if (cursor.Count > 0) { //data was already saved today and questions have been asked, so retrieve which ones have been asked
                cursor.MoveToLast (); //take the last entry of today
                alreadyAsked = cursor.GetInt(cursor.GetColumnIndex("QuestionFlags")); //retrieve value from last entry in db column QuestionFlags
            }
            insertValues.Put("QuestionFlags", alreadyAsked);
            dbMood.WritableDatabase.Insert ("MoodData", null, insertValues);

            //set the new alarm
            AlarmReceiverQuestionnaire temp = new AlarmReceiverQuestionnaire();
            temp.SetAlarm(context);

            w1.Release ();

            //check these pages for really waking up the device
            // http://stackoverflow.com/questions/6864712/android-alarmmanager-not-waking-phone-up
            // https://forums.xamarin.com/discussion/7490/alarm-manager

            //it's good to use the alarm manager for tasks that should last even days:
            // http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android/
        }
Beispiel #3
0
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, "NotificationReceiver");
            w1.Acquire ();

            //Toast.MakeText (context, "Received intent!", ToastLength.Short).Show ();
            var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService);
            var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            //Clicking the pending intent does not go to the Home Activity Screen, but to the last activity that was active before leaving the app
            var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(Home)), PendingIntentFlags.UpdateCurrent);
            //Notification should be language specific
            notification.SetLatestEventInfo (context, context.Resources.GetString(Resource.String.ReminderTitle), context.Resources.GetString(Resource.String.ReminderText), pendingIntent);
            notification.Flags |= NotificationFlags.AutoCancel;
            nMgr.Notify (0, notification);

            Vibrator vibrator = (Vibrator) context.GetSystemService(Context.VibratorService);
            if (vibrator != null)
                vibrator.Vibrate(400);

            w1.Release ();

            //check these pages for really waking up the device
            // http://stackoverflow.com/questions/6864712/android-alarmmanager-not-waking-phone-up
            // https://forums.xamarin.com/discussion/7490/alarm-manager

            //it's good to use the alarm manager for tasks that should last even days:
            // http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android/
        }
 public override void OnReceive(Context context, Intent intent)
 {
     var connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
     var info = connectivityManager.ActiveNetworkInfo;
     if (info != null && info.IsConnected)
     {
         //do stuff
         var wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
         var wifiInfo = wifiManager.ConnectionInfo;
         var ssid = wifiInfo.SSID;
         if (ssid == "\"jackstack\"")
         {
             var nMgr = (NotificationManager)context.GetSystemService(Context.NotificationService);
             //var notification = new Notification(Resource.Drawable.icon, $"Connected to {ssid}!");
             var pendingIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainActivity)), 0);
             //notification.SetLatestEventInfo(context, "Wifi Connected", "Wifi Connected Detail", pendingIntent);
             var notification = new Notification.Builder(context)
                 .SetSmallIcon(Resource.Drawable.icon)
                 .SetTicker($"Connected to {ssid}!")
                 .SetContentTitle("Wifi Connected")
                 .SetContentText("Wifi Connected Detail")
                 .SetContentIntent(pendingIntent)
                 .Build();
             nMgr.Notify(0, notification);
         }
     }
 }
 public override void OnReceive(Context c, Intent intent)
 {
     PowerManager pm = (PowerManager)c.GetSystemService(Context.PowerService);
     PowerManager.WakeLock wl = pm.NewWakeLock (WakeLockFlags.Partial, "Notificacion");
     wl.Acquire ();
     NotificationManager manager = (NotificationManager)c.GetSystemService (Context.NotificationService);
     Notification notification = new Notification (Resource.Drawable.icon, "Tareas pendientes");
     PendingIntent pendiente = PendingIntent.GetActivity (c, 0, new Intent (c, typeof(MainActivity)), 0);
     notification.SetLatestEventInfo (c, "Tareas pendientes", "Tienes tareas por hacer", pendiente);
     manager.Notify (0, notification);
     wl.Release ();
 }
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager powerManager = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "Notification Reciever");
            wakeLock.Acquire();

            var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
            var notification = new Notification(Resource.Drawable.Icon, "New Meeting");
            var pendingIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(SplashScreenActivity)), 0);
            notification.SetLatestEventInfo(context, "New Meeting", "There is an ACM meeting today.", pendingIntent);
            notificationManager.Notify(0, notification);
            wakeLock.Release();
        }
        public QuickAction(Context context, QuickActionLayout orientation)
        {
            _context = context;
            _window = new PopupWindow(context);
            _childPos = 0;

            _window.TouchIntercepted += HandleTouchIntercepted;
            _windowManager = context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();

            _orientation = orientation;
            _inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);

            SetRootViewId(orientation == QuickActionLayout.Horizontal ? Resource.Layout.popup_horizontal : Resource.Layout.popup_vertical);
        }
Beispiel #8
0
		public static bool checkNWConnection(Context ct)
		{
			ConnectivityManager connectivityManager = (ConnectivityManager)ct.GetSystemService (Context.ConnectivityService);
			NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
			bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
			return isOnline;
		}
Beispiel #9
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="context"></param>
        public LocationTracker(Context context, string provider = LocationManager.GpsProvider)
        {
            locationMan = (LocationManager)context.GetSystemService(Service.LocationService);

            if(locationMan.GetProviders(true).Contains(provider))
            {
                Provider = provider;
            }
            else if (locationMan.IsProviderEnabled(LocationManager.GpsProvider))
            {
                Provider = LocationManager.GpsProvider;
            }
            else if (locationMan.IsProviderEnabled(LocationManager.NetworkProvider))
            {
                Provider = LocationManager.NetworkProvider;
            }
            else
            {
                Criteria crit = new Criteria();
                crit.Accuracy = Accuracy.Fine;
                Provider = locationMan.GetBestProvider(crit, true);
            }

            LastGPSReceived = DateTime.MinValue;
        }
Beispiel #10
0
		public static void Vibrate(Context context)
		{
			// Get instance of Vibrator from current Context
			Vibrator v = (Vibrator) context.GetSystemService(Context.VibratorService);
			// Vibrate for 400 milliseconds
			v.Vibrate(400);
		}
		/**
     * Constructs a feature view by inflating layout/feature.xml.
     */
		public FeatureView (Context context) 
			: base (context)
		{
			LayoutInflater layoutInflater =
				(LayoutInflater) context.GetSystemService (Context.LayoutInflaterService);
			layoutInflater.Inflate (Resource.Layout.feature, this);
		}
 private void initViews(Context context)
 {
     LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
     inflater.Inflate(R.Layout.residemenu_item, this);
     iv_icon = (ImageView)FindViewById(R.Id.iv_icon);
     tv_title = (TextView)FindViewById(R.Id.tv_title);
 }
Beispiel #13
0
        public static void Initialize(Context ctx)
        {
            P2PManager.ctx = ctx;

            if (intentFilter == null)
            {
                intentFilter = new IntentFilter();

                intentFilter.AddAction(WifiP2pManager.WifiP2pStateChangedAction);
                intentFilter.AddAction(WifiP2pManager.WifiP2pPeersChangedAction);
                intentFilter.AddAction(WifiP2pManager.WifiP2pConnectionChangedAction);
                intentFilter.AddAction(WifiP2pManager.WifiP2pThisDeviceChangedAction);
            }
            if (manager == null)
            {
                manager = (WifiP2pManager)ctx.GetSystemService(Context.WifiP2pService);
                channel = manager.Initialize(ctx, ctx.MainLooper, null);
            }
            if (receiver == null)
            {
                receiver = new WiFiDirectBroadcastReceiver(manager, channel);
            }

            ctx.RegisterReceiver(receiver, intentFilter);
        }
Beispiel #14
0
        public static void PullCurrentGames(Context context, Action<GamesJson> callback)
        {
            Task<bool>.Factory.StartNew(
                                   () =>
                                   {
                                       try
                                       {


                                           var connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
                                           var activeConnection = connectivityManager.ActiveNetworkInfo;
                                           if ((activeConnection != null) && activeConnection.IsConnected)
                                           {
                                               try
                                               {
                                                   GamesMobile.PullCurrentGames(callback);
                                                                                                  }
                                               catch (Exception ex)
                                               {
                                                   ErrorHandler.Save(ex, MobileTypeEnum.Android, context);
                                               }
                                           }


                                       }
                                       catch (Exception exception)
                                       {
                                           ErrorHandler.Save(exception, MobileTypeEnum.Android, context);
                                       }
                                       return true;
                                   });

        }
Beispiel #15
0
 public static void Initialize(Context ctx)
 {
     var wm = ctx.GetSystemService (Context.WindowService).JavaCast<IWindowManager> ();
     var displayMetrics = new DisplayMetrics ();
     wm.DefaultDisplay.GetMetrics (displayMetrics);
     density = displayMetrics.Density;
 }
Beispiel #16
0
 public static int ToPixels(Context context, float dips)
 {
     DisplayMetrics metrics = new DisplayMetrics();
     var wm = context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
     wm.DefaultDisplay.GetMetrics(metrics);
     return (int) (dips*((float) metrics.DensityDpi/160)); // px = dp * (dpi / 160)
 }
        public static void Save(Exception e, MobileTypeEnum mobileType, Context context, ErrorGroupEnum? errorGroup = null, ErrorSeverityEnum? errorSeverity = null, IList<Expression<Func<object>>> parameters = null, string additionalInformation = null)
        {
            Task<bool>.Factory.StartNew(
                                    () =>
                                    {
                                        try
                                        {
                                            string dt = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
                                            //string version = MobileTypeEnum.Android.ToString() + ":" + MobileConfig.MOBILE_VERSION_NUMBER_ANDROID;
                                            
                                            var stream = ErrorManagerMobile.SaveErrorObject(e, e.GetType(), additionalInformation:  additionalInformation + LoggerMobile.Instance.getLoggedMessages());

                                            var connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
                                            var activeConnection = connectivityManager.ActiveNetworkInfo;
                                            if ((activeConnection != null) && activeConnection.IsConnected)
                                            {
                                                try
                                                {
                                                    var response = Network.SendPackage(stream, ServerConfig.ERROR_SUBMIT_URL);
                                                   
                                                    
                                                }
                                                catch (Exception ex)
                                                {
                                                  
                                                }
                                            }
                                        }
                                        catch (Exception exception)
                                        {

                                        }
                                        return true;
                                    });
        }
 public void CancelAlarm(Context context)
 {
     Intent intent = new Intent(context, this.Class);
     PendingIntent sender = PendingIntent.GetBroadcast(context, 0, intent, 0);
     AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
     alarmManager.Cancel(sender);
 }
Beispiel #19
0
        public void CloseKeyboard(EditText editText)
        {
            //close the keyboard - MAKE GENERAL
            InputMethodManager imm = (InputMethodManager)Context.GetSystemService("input_method");

            imm.HideSoftInputFromWindow(editText.WindowToken, 0);
        }
 public void SetAlarm(Context context)
 {
     AlarmManager alarmMgr = (AlarmManager)context.GetSystemService(Context.AlarmService);
     Intent intent = new Intent(context, this.Class);
     PendingIntent alarmIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);
     //here I have to figure out what time it is now and what would be an appropriate time for the new alarm
     //in which time window are we now? set an alarm in the next one (random). Have it go off at least 11 minutes
     //before the next window to ensure that we will end up here again even if the invalidation timer goes off as well
     //use five 2.5 h windows starting from 9 and ending at 21.30
     //This returns the total amount of hours since midnight as a fraction, meaning that 16:30 is 16.5:
     //DateTime.Now.TimeOfDay.TotalHours
     double tempNow = DateTime.Now.TimeOfDay.TotalHours;
     double timeLeftTillNextWindow = 0;
     if ((tempNow >= 0f) & (tempNow < 9f))
         timeLeftTillNextWindow = 9f - tempNow;
     if ((tempNow >= 9f) & (tempNow < 11.5f))
         timeLeftTillNextWindow = 11.5f - tempNow;
     if ((tempNow >= 11.5f) & (tempNow < 14f))
         timeLeftTillNextWindow = 14f - tempNow;
     if ((tempNow >= 14f) & (tempNow < 16.5f))
         timeLeftTillNextWindow = 16.5f - tempNow;
     if ((tempNow >= 16.5f) & (tempNow < 19f))
         timeLeftTillNextWindow = 19f - tempNow;
     if ((tempNow >= 19f) & (tempNow < 24f))
         timeLeftTillNextWindow = 24f - tempNow + 9f; //wait till next morning
     //add a random amount between 5 minutes and (2.5 hours - 11 minutes = 150 - 11 = 139 minutes)
     Random rnd = new Random(); //generator is seeded each time it is initialized
     double offset = (double) rnd.Next(5, 139);
     //add the times
     offset += timeLeftTillNextWindow * 60; //times 60 to convert from hours to minutes
     //truncated by converting to int
     long offsetLong = (int)offset;
     //System.Console.WriteLine ("Time Left: " + timeLeftTillNextWindow.ToString () + " Random + Time: " + offsetLong.ToString ());
     alarmMgr.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + offsetLong * 60 * 1000, alarmIntent);
 }
Beispiel #21
0
		public UpdateChecker(Context ctx, DataBaseWrapper db, Setting setting) {
			if (string.IsNullOrEmpty (setting.NewestVersion)) {
				setting.NewestVersion = Setting.CurrentVersion;
			}
			var connectivityManager = (ConnectivityManager)ctx.GetSystemService(Context.ConnectivityService);
			if (setting.Synchronisation != Setting.Frequency.wlan || connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).GetState() == NetworkInfo.State.Connected) {
				new Thread (async () => {
					string contentsTask;
					try {
						using(var httpClient = new HttpClient()) {
							contentsTask = await httpClient.GetStringAsync ("https://raw.githubusercontent.com/Bla-Chat/Android/master/version.txt");
						}
					} catch (Exception e) {
						Log.Error ("BlaChat", e.StackTrace);
						contentsTask = null;
					} finally {
						//semaphore.Release ();
					}
					if (contentsTask != null) {
						setting.NewestVersion = contentsTask;
						db.Update(setting);
					}
				}).Start ();
			}
		}
Beispiel #22
0
		public override void OnReceive(Context context, Intent intent)
		{
			Android.Util.Log.Info("MonoGame", intent.Action.ToString());
			if(intent.Action == Intent.ActionScreenOff)
			{
				ScreenReceiver.ScreenLocked = true;
				MediaPlayer.IsMuted = true;
			}
			else if(intent.Action == Intent.ActionScreenOn)
			{
                // If the user turns the screen on just after it has automatically turned off, 
                // the keyguard will not have had time to activate and the ActionUserPreset intent
                // will not be broadcast. We need to check if the lock is currently active
                // and if not re-enable the game related functions.
                // http://stackoverflow.com/questions/4260794/how-to-tell-if-device-is-sleeping
                KeyguardManager keyguard = (KeyguardManager)context.GetSystemService(Context.KeyguardService);
                if (!keyguard.InKeyguardRestrictedInputMode())
                {
                    ScreenReceiver.ScreenLocked = false;
                    MediaPlayer.IsMuted = false;
                }
			}
			else if(intent.Action == Intent.ActionUserPresent)
			{
                // This intent is broadcast when the user unlocks the phone
				ScreenReceiver.ScreenLocked = false;
				MediaPlayer.IsMuted = false;
			}
		}
Beispiel #23
0
        public Adapter(Context appContext)
        {
            ScanTimeout = TimeSpan.FromSeconds(10); // default timeout is 10 seconds
            _appContext = appContext;
            // get a reference to the bluetooth system service
            this._manager = appContext.GetSystemService("bluetooth").JavaCast<BluetoothManager>();
            this._adapter = this._manager.Adapter;

            this._gattCallback = new GattCallback(this);

            this._gattCallback.DeviceConnected += (object sender, DeviceConnectionEventArgs e) =>
            {
                if (ConnectedDevices.Find((BluetoothDevice)e.Device.NativeDevice) == null)
                {
                    _connectedDevices.Add(e.Device);
                    this.DeviceConnected(this, e);
                }
            };

            this._gattCallback.DeviceDisconnected += (object sender, DeviceConnectionEventArgs e) =>
            {
                var device = ConnectedDevices.Find((BluetoothDevice)e.Device.NativeDevice);
                if (device != null)
                {
                    _connectedDevices.Remove(device);
                    this.DeviceDisconnected(this, e);
                }
            };
        }
Beispiel #24
0
        public static void PullSkater(string memberId, Context context, Action<SkaterJson> callback)
        {
            Task<bool>.Factory.StartNew(
                                   () =>
                                   {
                                       try
                                       {
                                           var profile = new SqlFactory().GetSkaterProfile(memberId);
                                           if (profile != null && profile.GotExtendedContent)
                                           {
                                               callback(profile);
                                               return true;
                                           }
                                           var connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
                                           var activeConnection = connectivityManager.ActiveNetworkInfo;
                                           if ((activeConnection != null) && activeConnection.IsConnected)
                                           {
                                               try
                                               {
                                                   SkatersMobile.PullPublicSkater(memberId, callback);
                                               }
                                               catch (Exception ex)
                                               {
                                                   ErrorHandler.Save(ex, MobileTypeEnum.Android, context);
                                               }
                                           }
                                       }
                                       catch (Exception exception)
                                       {
                                           ErrorHandler.Save(exception, MobileTypeEnum.Android, context);
                                       }
                                       return true;
                                   });

        }
Beispiel #25
0
        public static void SearchShopItems(int page, int count, string s, Context context, Action<ShopsJson> callback)
        {
            Task<bool>.Factory.StartNew(
                                   () =>
                                   {
                                       try
                                       {


                                           var connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
                                           var activeConnection = connectivityManager.ActiveNetworkInfo;
                                           if ((activeConnection != null) && activeConnection.IsConnected)
                                           {
                                               try
                                               {
                                                   ShopMobile.SearchShopItems(page, count, s, callback);
                                               }
                                               catch (Exception ex)
                                               {
                                                   ErrorHandler.Save(ex, MobileTypeEnum.Android, context);
                                               }
                                           }
                                       }
                                       catch (Exception exception)
                                       {
                                           ErrorHandler.Save(exception, MobileTypeEnum.Android, context);
                                       }
                                       return true;
                                   });

        }
        public static async Task<ConnectionResult> ConnectAsync(Context context, Ssid ssid, TimeSpan checkInterval, TimeSpan timeout)
        {
            Logger.Verbose("WifiConnector.Connecting");

            var wifiManager = context.GetSystemService(Context.WifiService).JavaCast<WifiManager>();
            EnsureWifiEnabled(wifiManager);
            if (IsConnectedToNetwork(wifiManager, ssid))
            {
                Logger.Info($"Network {ssid} already connected");
                return ConnectionResult.AlreadyConnected;
            }

            var network = GetConfiguredNetwork(wifiManager, ssid);
            EnsureDifferentNetworksNotActive(wifiManager, network);
            EnsureNetworkReachable(wifiManager, ssid);

            ActivateNetwork(wifiManager, network);
            Reconnect(wifiManager);

            Logger.Verbose($"Connection to network {ssid} requested");
            
            var result = await WaitUntilConnectedAsync(wifiManager, network, checkInterval, timeout);
            Logger.Info(result == ConnectionResult.Connected
                ? $"Connected to {ssid.Quoted}"
                : $"Not yet connected to {ssid.Quoted}. Try increase a connection timeout");
            return result;
        }
        public static void PullEventsByLocation(int page, int count, double longitude, double latitude, Context context, Action<EventsJson> callback)
        {
            Task<bool>.Factory.StartNew(
                                   () =>
                                   {
                                       try
                                       {


                                           var connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
                                           var activeConnection = connectivityManager.ActiveNetworkInfo;
                                           if ((activeConnection != null) && activeConnection.IsConnected)
                                           {
                                               try
                                               {
                                                   CalendarMobile.PullCurrentEventsByLocation(page, count, longitude, latitude, callback);
                                               }
                                               catch (Exception ex)
                                               {
                                                   ErrorHandler.Save(ex, MobileTypeEnum.Android, context);
                                               }
                                           }


                                       }
                                       catch (Exception exception)
                                       {
                                           ErrorHandler.Save(exception, MobileTypeEnum.Android, context);
                                       }
                                       return true;
                                   });

        }
Beispiel #28
0
 public static void ShowKeyboard(Context context, View pView)
 {
     pView.RequestFocus();
     InputMethodManager inputMethodManager = (InputMethodManager)context.GetSystemService (Context.InputMethodService);
     inputMethodManager.ShowSoftInput(pView, ShowFlags.Forced);
     inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
 }
        public static bool HasWifi(Context ctx)
        {
            var con = (ConnectivityManager)ctx.GetSystemService(Context.ConnectivityService);
            var wifi = con.GetNetworkInfo(ConnectivityType.Wifi);

            return wifi != null && wifi.GetState() == NetworkInfo.State.Connected;
        }
		private void CreateNotifications(Context context, string action, bool isMessageNeeded = true, bool isToastNeeded = true)
		{
			#if DEBUG
			try {
				if (isMessageNeeded)
				{
					Notification notification = new Notification.Builder(context)
						.SetContentTitle ("BluetoothNotify intent received " + action)
						.SetContentText ("message sent at" + System.DateTime.Now.ToLongTimeString ())
						.SetSmallIcon (Resource.Drawable.icon)
						.Build ();

					NotificationManager nMgr = (NotificationManager)context.GetSystemService (Android.Content.ContextWrapper.NotificationService);
					nMgr.Notify (0, notification);
				}

				if (isToastNeeded)
				{
					var myHandler = new Handler ();
					myHandler.Post (() =>  {
						Toast.MakeText (context, "BluetoothNotify intent received " + action, ToastLength.Long).Show ();
					});
				}
				
			} catch (Exception ex) {
				Log.Info ("com.tarabel.bluetoothnotify", "CreateNotification error in IntentReceiver " + ex.ToString());
			}
			#endif
		}
 public AccelerometerManager(Context context, IAccelerometerListener listener)
 {
     this.context = context;
       eventListener = new ShakeSensorEventListener(listener);
       sensorManager = (SensorManager) context.GetSystemService(Context.SensorService);
       IsSupported = sensorManager.GetSensorList(SensorType.Accelerometer).Count > 0;
 }
        public override ObjectAnimator GetAppearingAnimator(Android.Content.Context context)
        {
            Point          outPoint = new Point();
            IWindowManager wm       = context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();

            wm.DefaultDisplay.GetSize(outPoint);

            ObjectAnimator animator = ObjectAnimator.OfPropertyValuesHolder(
                PropertyValuesHolder.OfFloat("alpha", 0f, 1f),
                PropertyValuesHolder.OfFloat("translationY", outPoint.Y / 2f, 0f),
                PropertyValuesHolder.OfFloat("rotation", -45f, 0f));

            animator.SetDuration((long)(200 * mSpeedFactor));
            return(animator);
        }
 public AppListAdapter(Android_Content.Context context)
     : base(context, global::Android.R.Layout.Simple_list_item_2)
 {
     mInflater = (LayoutInflater)context.GetSystemService(Android_Content.Context.LAYOUT_INFLATER_SERVICE);
 }
 public MyAdapter(Context context)
 {
     Context  = context;
     Inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
     Owner    = (Main)context;
 }