示例#1
0
        public override void OnReceive(Context context, Intent intent)
        {
            if (intent != null)
            {
                String data = intent.GetStringExtra(BARCODE_VALUE);
                String typeString = intent.GetStringExtra(BARCODE_TYPE);
                Symbology symbology = Symbology.UNKNOWN;
                switch (typeString.ToUpper())
                {
                    case "UPCE":
                        symbology = Symbology.UPCE;
                        break;
                    case "EAN13":
                        symbology = Symbology.EAN13;
                        break;
                    case "EAN8":
                        symbology = Symbology.EAN8;
                        break;
                    default:
                        symbology = Symbology.UNKNOWN;
                        break;
                }

                RedLaser.Instance.TriggerScan(data, symbology);
                Log.Info("MonoCross", "response received from scan " + data + " : " + typeString);
            }
            else
            {
                Log.Warn("MonoCross", "weird response received");
            }
        }
示例#2
0
		protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
		{

			base.OnActivityResult (requestCode, resultCode, data);

			switch (resultCode) {
			case Result.Ok:

				AppCommon.Inst.FbAccessToken = data.GetStringExtra ("AccessToken");
				string error = data.GetStringExtra ("Exception");

				// TODO Localization for facebook errors
				if (!string.IsNullOrEmpty(error))
					Utils.Alert (this, "Failed to Log In", "Reason: " + error, false);
				else {
					try
					{
						AppCommon.Inst.InitUser (data.GetStringExtra ("UserId"));
						this.StartNextActivity<ReqBookingSrcActivity> ();
					}
					catch(TException ex) 
					{
						Utils.HandleTException (this, ex);
					}
				}
				break;
			case Result.Canceled:
				Utils.Alert (this, "Failed to Log In", "User Cancelled", false);
				break;
			default:
				break;
			}
		}
示例#3
0
		public static int main(Intent i){
			switch (i.GetIntExtra("previous",3)) { // This value shows which is the previous activity, with: 0-MainActivity/1-VertexActivity/2-EdgeActivity/3-Any other
			case 0:
				initiate(i);
				break;
			case 1:
				switch (graph.addVertex(i.GetStringExtra("vertex"))) {
				case -1:
					return 1;
				case -2:
					return 6;
				default:
					return 2;
				}
			case 2:
				switch (graph.addEdge(i.GetIntExtra("weight", -1),i.GetStringExtra("start"),i.GetStringExtra("end"))){
				case -1:
					return 1;
				case -2:
					return 3;
				case -3:
					return 4;
				case -4:
					return 7; //Do not accept weight 0
				default:
					return 5;
				}
			}
			return 0;
		}
		protected async void HandleRegistration(Context context, Intent intent)
		{
			string registrationId = intent.GetStringExtra("registration_id");
			string error = intent.GetStringExtra("error");
			string unregistration = intent.GetStringExtra("unregistered");

			var nMgr = (NotificationManager)GetSystemService (NotificationService);

			if (!String.IsNullOrEmpty (registrationId)) {
				NativeRegistration = await Hub.RegisterNativeAsync (registrationId, new[] {"Native"});

				var notificationNativeRegistration = new Notification (Resource.Drawable.Icon, "Native Registered");
				var pendingIntentNativeRegistration = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
				notificationNativeRegistration.SetLatestEventInfo (this, "Native Reg.-ID", NativeRegistration.RegistrationId, pendingIntentNativeRegistration);
				nMgr.Notify (_messageId, notificationNativeRegistration);
				_messageId++;
			}
			else if (!String.IsNullOrEmpty (error)) {
				var notification = new Notification (Resource.Drawable.Icon, "Gcm Registration Failed.");
				var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
				notification.SetLatestEventInfo (this, "Gcm Registration Failed", error, pendingIntent);
				nMgr.Notify (_messageId, notification);
				_messageId++;
			}
			else if (!String.IsNullOrEmpty (unregistration)) {
				if (NativeRegistration != null)
					await Hub.UnregisterAsync (NativeRegistration);

				var notification = new Notification (Resource.Drawable.Icon, "Unregistered successfully.");
				var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
				notification.SetLatestEventInfo (this, "MyIntentService", "Unregistered successfully.", pendingIntent);
				nMgr.Notify (_messageId, notification);
				_messageId++;
			}
		}
示例#5
0
			/// <param name="context">The Context in which the receiver is running.</param>
			/// <param name="intent">The Intent being received.</param>
			/// <summary>
			/// This method is called when the BroadcastReceiver is receiving an Intent
			///  broadcast.
			/// </summary>
			public override void OnReceive (Context context, Intent intent)
			{
				//get action from intent
				string action = intent.Action;
				//get command from action
				string cmd = intent.GetStringExtra("command");
				//write info
				Console.WriteLine("mIntentReceiver.onReceive " + action + " / " + cmd);
				//get artist from intent
				String artist = intent.GetStringExtra("artist");
				//get album from intent
				String album = intent.GetStringExtra("album");
				//get track from intent
				String track = intent.GetStringExtra("track");
				//write all info
				Console.WriteLine(artist+":"+album+":"+track);

				//set content title to notification builder
				builder.SetContentTitle (artist);
				//set contennt text to notification builder
				builder.SetContentText (track+"-"+album);
				//set big style to builder
				builder.SetStyle (new NotificationCompat.BigTextStyle ().BigText (track + "-" + album));
				try
				{
					//seach album thumbnail from itunes api
					var json = new System.Net.WebClient().DownloadString("http://itunes.apple.com/search?term=" + Uri.EscapeDataString(track+" "+album+" "+artist) + "&country=mx&limit=1&entity=song");
					//parse json downloaded to json object
					Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json);
					//get json results child
					var n = o["results"];
					//get firts "artworkUrl100" property
					string val = (string)n[0]["artworkUrl100"];
					//check if exist thumbnail
					if (string.IsNullOrEmpty(val))
					{
						//if thumbnail doesnt exists set default image to largeicon
						builder.SetLargeIcon(BitmapFactory.DecodeResource(null,Resource.Drawable.ic_launcher));
					}
					else
					{
						//change 100x100 size of thumbnail to 600x600 image
						StringBuilder builde = new StringBuilder(val);
						builde.Replace("100x100", "600x600");
						//webclient to download image
						WebClient c = new WebClient();
						//downloadimage to bytearray
						byte[] data = c.DownloadData(builde.ToString());
						//convert byte[] downloaded to bitmap and set large icon to builder
						builder.SetLargeIcon(Bitmap.CreateScaledBitmap(BitmapFactory.DecodeByteArray(data,0,data.Length),150,150,false));
					}
				}
				catch(Exception e)
				{
					//set default image to largeicon
					builder.SetLargeIcon(BitmapFactory.DecodeResource(null,Resource.Drawable.ic_launcher));
				}
				//update/create a notification
				notificationManager.Notify(0, builder.Build());
			}
		private const long WIDGET_REFRESH_DELAY_MS = 5000; //5 Seconds


			public override void OnReceive(Context context, Intent intent) {

			// Refresh the widget after a push comes in
			if (PushManager.ActionPushReceived == intent.Action) {
				RichPushWidgetUtils.RefreshWidget(context, WIDGET_REFRESH_DELAY_MS);
			}

			// Only takes action when a notification is opened
			if (PushManager.ActionNotificationOpened != intent.Action) {
				return;
			}

			// Ignore any non rich push notifications
			if (!RichPushManager.IsRichPushMessage(intent.Extras)) {
				return;
			}

			string messageId = intent.GetStringExtra(EXTRA_MESSAGE_ID_KEY);
			Logger.Debug("Notified of a notification opened with id " + messageId);

			Intent messageIntent = null;

			// Set the activity to receive the intent
			if ("home" == intent.GetStringExtra(ACTIVITY_NAME_KEY)) {
				messageIntent = new Intent(context, typeof (MainActivity));
			} else {
				// default to the Inbox
				messageIntent =  new Intent(context, typeof (InboxActivity));
			}

			messageIntent.PutExtra(RichPushApplication.MESSAGE_ID_RECEIVED_KEY, messageId);
			messageIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop | ActivityFlags.NewTask);
			context.StartActivity(messageIntent);
		}
示例#7
0
        public override void OnReceive(Context context, Intent intent)
        {
            var id = intent.GetStringExtra("id");
            var message = intent.GetStringExtra("message");
            var title = intent.GetStringExtra("title");

            var notIntent = new Intent(context, typeof(MainActivity));
            notIntent.PutExtra("id", id);
            var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
            var manager = NotificationManagerCompat.From(context);

            int resourceId = Resource.Drawable.ic_launcher_xx;

            var wearableExtender = new NotificationCompat.WearableExtender()
                .SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId));

            //Generate a notification with just short text and small icon
            var builder = new NotificationCompat.Builder(context)
                            .SetContentIntent(contentIntent)
                            .SetSmallIcon(Resource.Drawable.ic_launcher_xx)
                            .SetContentTitle(title)
                            .SetContentText(message)
                            .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                            .SetAutoCancel(true)
                            .Extend(wearableExtender);

            var notification = builder.Build();
            manager.Notify(int.Parse(id), notification);
        }
示例#8
0
        protected override void OnHandleIntent(Intent intent)
        {
            try {
                Context context = this.ApplicationContext;
                string action = intent.Action;

                if (action.Equals ("com.google.android.c2dm.intent.REGISTRATION")) {
                    MainActivity.appRegID = intent.GetStringExtra ("registration_id");
                    Console.WriteLine(intent.GetStringExtra ("registration_id"));
                } else if (action.Equals ("com.google.android.c2dm.intent.RECEIVE")) {

            //					PendingIntent resultPendingIntent = PendingIntent.GetActivity(context,0,new Intent(context,typeof(MainActivity)),0);
            //					// Build the notification
            //					NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            //						.SetAutoCancel(true)
            //							.SetContentIntent(resultPendingIntent)
            //							.SetContentTitle("新通知來了")
            //							.SetSmallIcon(Resource.Drawable.xsicon)
            //							.SetContentText(intent.GetStringExtra("alert"));
            //
            //					NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
            //					notificationManager.Notify(0, builder.Build());
                    createNotification("您有新的信息",intent.GetStringExtra("alert"));
                }
            } finally {
                lock (LOCK) {
                    //Sanity check for null as this is a public method
                    if (sWakeLock != null)
                        sWakeLock.Release ();
                }
            }
        }
示例#9
0
        public override void OnReceive(Context context, Intent intent)
        {
            string message = intent.GetStringExtra("message");
            string title = intent.GetStringExtra("title");

            Intent notIntent = new Intent(context, typeof(NotificationService));

            PendingIntent contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
            NotificationManager manager = NotificationManager.FromContext(context);

            var bigTextStyle = new Notification.BigTextStyle()
                        .SetBigContentTitle(title)
                        .BigText(message);

            Notification.Builder builder = new Notification.Builder(context)
                .SetContentIntent(contentIntent)
                .SetSmallIcon(Resource.Drawable.icon)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetStyle(bigTextStyle)
                .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                .SetAutoCancel(true)
                .SetPriority((int)NotificationPriority.High)
                .SetVisibility(NotificationVisibility.Public)
                .SetDefaults(NotificationDefaults.Vibrate)
                .SetCategory(Notification.CategoryAlarm);

            if (!MainActivity.IsActive)
            {
                manager.Notify(0, builder.Build());
                StartWakefulService(context, notIntent);
            }
        }
示例#10
0
        public override void OnReceive(Context context, Intent intent)
        {
            var message = new SmsMessage {
                Text = intent.GetStringExtra ("messageText"),
                SmsGroupId = intent.GetIntExtra ("smsGroupId", -1),
                ContactAddressBookId = intent.GetStringExtra ("addressBookId"),
                ContactName = intent.GetStringExtra ("contactName"),
                SentDate = DateTime.Parse (intent.GetStringExtra ("dateSent"))
            };

            switch ((int)ResultCode)
            {
                case (int)Result.Ok:
                    _messageRepo = new Repository<SmsMessage>();
                    _messageRepo.Save (message);
                    Toast.MakeText (context, string.Format ("Message sent to {0}", message.ContactName), ToastLength.Short).Show ();
                    break;
                case (int)global::Android.Telephony.SmsResultError.NoService:
                case (int)global::Android.Telephony.SmsResultError.RadioOff:
                case (int)global::Android.Telephony.SmsResultError.NullPdu:
                case (int)global::Android.Telephony.SmsResultError.GenericFailure:
                default:
                    Toast.MakeText (context, string.Format("Doh! Message could not be sent to {0}.", message.ContactName),
                                ToastLength.Short).Show ();
                    break;
            }
            _messageRepo = null;
        }
示例#11
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);
 }
        /// <inheritdoc/>
        public override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            ZTnTrace.Trace(MethodBase.GetCurrentMethod());

            switch (requestCode)
            {
                case AddNewAccount:
                    switch (resultCode)
                    {
                        case -1:
                            var battleTag = data.GetStringExtra("battleTag");
                            var host = data.GetStringExtra("host");

                            D3Context.Instance.DbAccounts.Insert(battleTag, host);

                            IListAdapter careerAdapter = new SimpleCursorAdapter(Activity, Android.Resource.Layout.SimpleListItem2, cursor, accountsFromColumns, accountsToId);
                            Activity.FindViewById<ListView>(Resource.Id.AccountsListView)
                                .Adapter = careerAdapter;

                            Toast.MakeText(Activity, "Account added", ToastLength.Short)
                                .Show();
                            break;
                    }
                    break;
            }

            base.OnActivityResult(requestCode, resultCode, data);
        }
 /// <summary>
 /// This is the entry point for all asynchronous messages sent from Android Market to
 /// the application. This method forwards the messages on to the
 /// <seealso cref="BillingService"/>, which handles the communication back to Android Market.
 /// The <seealso cref="BillingService"/> also reports state changes back to the application through
 /// the <seealso cref="ResponseHandler"/>.
 /// </summary>
 public override void OnReceive(Context context, Intent intent)
 {
     string action = intent.Action;
     if (Consts.ACTION_PURCHASE_STATE_CHANGED.Equals(action))
     {
         string signedData = intent.GetStringExtra(Consts.INAPP_SIGNED_DATA);
         string signature = intent.GetStringExtra(Consts.INAPP_SIGNATURE);
         purchaseStateChanged(context, signedData, signature);
     }
     else if (Consts.ACTION_NOTIFY.Equals(action))
     {
         string notifyId = intent.GetStringExtra(Consts.NOTIFICATION_ID);
         if (Consts.DEBUG)
         {
             Log.Info(TAG, "notifyId: " + notifyId);
         }
         notify(context, notifyId);
     }
     else if (Consts.ACTION_RESPONSE_CODE.Equals(action))
     {
         long requestId = intent.GetLongExtra(Consts.INAPP_REQUEST_ID, -1);
         int responseCodeIndex = intent.GetIntExtra(Consts.INAPP_RESPONSE_CODE, (int)Consts.ResponseCode.RESULT_ERROR);
         checkResponseCode(context, requestId, responseCodeIndex);
     }
     else
     {
         Log.Warn(TAG, "unexpected action: " + action);
     }
 }
示例#14
0
        public static AppNotification ReadNotification(Intent intent)
        {
            var t = intent.GetStringExtra ("Type");
            if (t == null)
                t = intent.GetStringExtra ("event");
            if (t == null)
                return new UnknownNotification ();

            Type type;
            if (!notificationTypes.TryGetValue (t, out type))
                return new UnknownNotification ();

            var not = (AppNotification)Activator.CreateInstance (type);

            foreach (var p in not.GetType ().GetProperties (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)) {
                var arg = (IntentArg) Attribute.GetCustomAttribute (p, typeof(IntentArg));
                if (arg != null) {
                    object val = GetValue (intent, arg.Name ?? p.Name, p.PropertyType);
                    p.SetValue (not, val, null);
                }
            }

            foreach (var p in not.GetType ().GetFields (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)) {
                var arg = (IntentArg) Attribute.GetCustomAttribute (p, typeof(IntentArg));
                if (arg != null) {
                    object val = GetValue (intent, arg.Name ?? p.Name, p.FieldType);
                    p.SetValue (not, val);
                }
            }
            return not;
        }
		public override void OnReceive (Context context, Intent intent) {
			if (RetreiveLatestReceiver.IsAvailableVersion(context)) {
				intent.PutExtra ("title", string.Format(context.Resources.GetString(Resource.String.notification_title), "WhatsApp " + RetreiveLatestReceiver.GetLatestVersion ()));
				intent.PutExtra ("message", string.Format(context.Resources.GetString(Resource.String.notification_description), context.Resources.GetString(Resource.String.app_name)));
				var message = intent.GetStringExtra ("message");
				var title = intent.GetStringExtra ("title");

				var notIntent = new Intent (context, typeof(MainActivity));
				var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
				var manager = NotificationManagerCompat.From (context);

				var style = new NotificationCompat.BigTextStyle ().BigText (message);
				int resourceId = Resource.Drawable.ic_launcher;

				var wearableExtender = new NotificationCompat.WearableExtender ().SetBackground (BitmapFactory.DecodeResource (context.Resources, resourceId));

				// Generate notification (short text and small icon)
				var builder = new NotificationCompat.Builder (context);
				builder.SetContentIntent (contentIntent);
				builder.SetSmallIcon (Resource.Drawable.ic_launcher);
				builder.SetContentTitle (title);
				builder.SetContentText (message);
				builder.SetStyle (style);
				builder.SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis ()); // When the AlarmManager will check changes?
				builder.SetAutoCancel (true);
				builder.Extend (wearableExtender); // Support Android Wear, yeah!

				var notification = builder.Build ();
				manager.Notify (0, notification);
			}
		}
		public override void OnReceive (Context context, Intent intent)
		{
			var message = intent.GetStringExtra("message");
			var title = intent.GetStringExtra("title");

			var notIntent = new Intent(context, typeof(MainScreen));
			var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
			var manager = NotificationManagerCompat.From(context);

			var style = new NotificationCompat.BigTextStyle();
			style.BigText(message);

			int resourceId = Resource.Drawable.HappyBaby;

			var wearableExtender = new NotificationCompat.WearableExtender()
				.SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId));

			//Generate a notification with just short text and small icon
			var builder = new NotificationCompat.Builder(context)
				.SetContentIntent(contentIntent)
				.SetSmallIcon(Resource.Drawable.HappyBaby)
				.SetSound(Android.Net.Uri.Parse("android.resource://com.iinotification.app/"+ Resource.Raw.babySound))
				.SetContentTitle("Hey Mom")
				.SetContentText("Here I'm :)")
				.SetStyle(style)
				.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
				.SetAutoCancel(true)
				.Extend(wearableExtender);

			var notification = builder.Build();
			manager.Notify(0, notification);
		}
        // Creates a new notification depending on makeHeadsUpNotification.
        public Notification CreateNotification(Context context, Intent intent)
        {
            // indicate that this sms comes from server
            intent.PutExtra ("source", "server");

            // Parse bundle extras
            string contactId = intent.GetStringExtra("normalizedPhone");
            string message = intent.GetStringExtra("message");

            // Getting contact infos
            var contact = Contact.GetContactByPhone (contactId, context);

            var builder = new Notification.Builder (context)
                .SetSmallIcon (Resource.Drawable.icon)
                .SetPriority ((int)NotificationPriority.Default)
                .SetCategory (Notification.CategoryMessage)
                .SetContentTitle (contact.DisplayName != "" ? contact.DisplayName : contactId)
                .SetContentText (message)
                .SetSound (RingtoneManager.GetDefaultUri (RingtoneType.Notification));

            var fullScreenPendingIntent = PendingIntent.GetActivity (context, 0,
                intent, PendingIntentFlags.CancelCurrent);
                builder.SetContentText (message)
                       .SetFullScreenIntent (fullScreenPendingIntent, true)
                       .SetContentIntent (fullScreenPendingIntent);

            return builder.Build ();
        }
        private void HandleRegistration(Intent intent)
        {
            string registrationId = intent.GetStringExtra("registration_id");
            string error = intent.GetStringExtra("error");
            string unregistration = intent.GetStringExtra("unregistered");

            if (string.IsNullOrEmpty(error))
                SNSUtils.RegisterDevice(SNSUtils.Platform.Android, registrationId);
        }
示例#19
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            var url = intent.GetStringExtra("url");
            var taskId = intent.GetStringExtra("taskId");

            Task.Run(() => {
            });

            return StartCommandResult.Sticky;
        }
        protected override void OnHandleIntent(Intent intent)
        {
            var context = ApplicationContext;
            if (intent.Action.Equals(ActionSendFile))
            {
                var fileUri = intent.GetStringExtra(ExtrasFilePath);
                var host = intent.GetStringExtra(ExtrasGroupOwnerAddress);
                var port = intent.GetIntExtra(ExtrasGroupOwnerPort, 8988);
                var socket = new Socket();

                try
                {
                    Log.Debug(WiFiDirectActivity.Tag, "Opening client socket - ");
                    socket.Bind(null);
                    socket.Connect(new InetSocketAddress(host, port), SocketTimeout);

                    Log.Debug(WiFiDirectActivity.Tag, "Client socket - " + socket.IsConnected);
                    var stream = socket.OutputStream;
                    var cr = context.ContentResolver;
                    Stream inputStream = null;
                    try
                    {
                        inputStream = cr.OpenInputStream(Android.Net.Uri.Parse(fileUri));
                    }
                    catch (FileNotFoundException e)
                    {
                        Log.Debug(WiFiDirectActivity.Tag, e.ToString());
                    }
                    DeviceDetailFragment.CopyFile(inputStream, stream);
                    Log.Debug(WiFiDirectActivity.Tag, "Client: Data written");
                }
                catch (IOException e)
                {
                    Log.Debug(WiFiDirectActivity.Tag, e.Message);
                }
                finally
                {
                    if (socket != null)
                    {
                        if (socket.IsConnected)
                        {
                            try
                            {
                                socket.Close();
                            }
                            catch (IOException e)
                            {
                                // Give up
                                Log.Debug(WiFiDirectActivity.Tag, "Gave up on closing socket " + e.StackTrace);
                            }
                        }
                    }
                }
            }
        }
示例#21
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);

            switch (resultCode)
            {
                case Result.Ok:
                {
                    accessToken = data.GetStringExtra("AccessToken");
                    string userId = data.GetStringExtra("UserId");
                    string error = data.GetStringExtra("Exception");

                    fb = new FacebookClient(accessToken);

                    ImageView imgUser = FindViewById<ImageView>(Resource.Id.imgUser);
                    TextView txtvUserName = FindViewById<TextView>(Resource.Id.txtvUserName);

                    fb.GetTaskAsync("me").ContinueWith(t =>
                    {
                        if (!t.IsFaulted)
                        {
                            var result = (IDictionary<string, object>)t.Result;

                            // available picture types: square (50x50), small (50xvariable height), large (about 200x variable height) (all size in pixels)
                            // for more info visit http://developers.facebook.com/docs/reference/api
                            string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", userId, "square", accessToken);
                            var bm = BitmapFactory.DecodeStream(new Java.Net.URL(profilePictureUrl).OpenStream());
                            string profileName = (string)result["name"];

                            RunOnUiThread(() =>
                            {
                                imgUser.SetImageBitmap(bm);
                                txtvUserName.Text = profileName;
                            });

                            isLoggedIn = true;
                        }
                        else
                        {
                            Alert("Failed to Log In", "Reason: " + error, false, (res) =>
                            {
                            });
                        }
                    });
                }
                break;
            case Result.Canceled:
                Alert ("Failed to Log In", "User Cancelled", false, (res) => {} );
                break;
            default:
                break;
            }
        }
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);
            if (resultCode == Result.Ok) {
                //helloLabel.Text = data.GetStringExtra ("greeting");
                String curUser = data.GetStringExtra ("username");
                String curPass = data.GetStringExtra ("password");

                this.usernames.Add (curUser);
                this.passwords.Add (curPass);
            }
        }
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            string cogida1 = intent.GetStringExtra("querry1");
            string cogida2 = intent.GetStringExtra("querry2");
            string cogida3 = intent.GetStringExtra("querry3");
            string cogida4 = intent.GetStringExtra("querry4");
            string cogida5 = intent.GetStringExtra("querry5");

            if (cogida1 == "si" && !YoutubePlayerServerActivity.gettearinstancia().envideo)
            {
                YoutubePlayerServerActivity.gettearinstancia().RunOnUiThread(() => {
                    YoutubePlayerServerActivity.gettearinstancia().imgPlay.CallOnClick();
                });
                // clasesettings.guardarsetting("cquerry", "playpause()");
            }
            else
            if (cogida2 == "si" && !YoutubePlayerServerActivity.gettearinstancia().envideo)
            {
                YoutubePlayerServerActivity.gettearinstancia().RunOnUiThread(() => {
                    YoutubePlayerServerActivity.gettearinstancia().imgNext.CallOnClick();
                });
                //  clasesettings.guardarsetting("cquerry", "siguiente()");
            }
            else
            if (cogida3 == "si" && !YoutubePlayerServerActivity.gettearinstancia().envideo)
            {
                YoutubePlayerServerActivity.gettearinstancia().RunOnUiThread(() => {
                    YoutubePlayerServerActivity.gettearinstancia().imgBack.CallOnClick();
                });
                //  clasesettings.guardarsetting("cquerry", "anterior()");
            }
            else
            if (cogida4 == "si" && !YoutubePlayerServerActivity.gettearinstancia().envideo)
            {
                YoutubePlayerServerActivity.gettearinstancia().RunOnUiThread(() => {
                    YoutubePlayerServerActivity.gettearinstancia().imgForeward.CallOnClick();
                });
                /// clasesettings.guardarsetting("cquerry", "adelantar()");
            }
            else
            if (cogida5 == "si" && !YoutubePlayerServerActivity.gettearinstancia().envideo)
            {
                YoutubePlayerServerActivity.gettearinstancia().RunOnUiThread(() => {
                    YoutubePlayerServerActivity.gettearinstancia().imgBackward.CallOnClick();
                });
                ///  clasesettings.guardarsetting("cquerry", "atrazar()");
            }



            this.StopSelf();
        }
示例#24
0
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            // This method executes on the main thread of the application.
            string        dotLogsSerialized = intent.GetStringExtra("dotLogs");
            List <DotLog> dotLogs           = JsonConvert.DeserializeObject <List <DotLog> >(dotLogsSerialized);

            string          positionsSerialized = intent.GetStringExtra("positions");
            List <Position> positions           = JsonConvert.DeserializeObject <List <Position> >(positionsSerialized);

            PostLogs(dotLogs, positions);

            return(StartCommandResult.NotSticky);
        }
示例#25
0
        public override void OnReceive(Context context, Intent i)
        {
            // check the intent action is for us
            if (i.Action.Equals (IntentAction)) {
                // define a string that will hold our output
                String Out = "";
                // get the source of the data
                String source = i.GetStringExtra (SOURCE_TAG);
                // save it to use later
                if (source == null)
                    source = "scanner";
                // get the data from the intent
                String data = i.GetStringExtra (DATA_STRING_TAG);
                // let's define a variable for the data length
                int data_len = 0;
                // and set it to the length of the data
                if (data != null)
                    data_len = data.Length;
                // check if the data has come from the barcode scanner
                if (source.Equals ("scanner")) {
                    // check if there is anything in the data
                    if (data != null && data.Length > 0) {
                        // we have some data, so let's get it's symbology
                        String sLabelType = i.GetStringExtra (LABEL_TYPE_TAG);
                        // check if the string is empty
                        if (sLabelType != null && sLabelType.Length > 0) {
                            // format of the label type string is LABEL-TYPE-SYMBOLOGY
                            // so let's skip the LABEL-TYPE- portion to get just the symbology
                            sLabelType = sLabelType.Substring (11);
                        } else {
                            // the string was empty so let's set it to "Unknown"
                            sLabelType = "Unknown";
                        }

                        // let's construct the beginning of our output string
                        // Out = "Scanner  " + "Symbology: " + sLabelType + ", Length: " + data_len.ToString () + ", Data: " + data.ToString () + "\r\n";
                        Out = "Scanner Data: " + data.ToString() + "\r\n";
                    }
                }
                // check if the data has come from the MSR
                if (source.Equals ("msr")) {
                    // construct the beginning of our output string
                    Out = "Source: MSR, Length: " + data_len.ToString () + ", Data: " + data.ToString () + "\r\n";
                }

                if (scanDataReceived != null) {
                    scanDataReceived (this, Out);
                }
            }
        }
 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     base.OnActivityResult (requestCode, resultCode, data);
     switch (requestCode) {
     case CAMMY:
         if (resultCode == Result.Ok) {
             string filename = data.GetStringExtra ("filename");
             if (!string.IsNullOrEmpty (filename)) {
                 using (Bitmap bmp = BitmapFactory.DecodeFile(filename)) {
                     if (bmp != null) {
                         using (MemoryStream ms = new MemoryStream ()) {
                             bmp.Compress (Bitmap.CompressFormat.Jpeg, 80, ms);
                             if (userImage == null)
                                 userImage = new byte[ms.Length];
                             userImage = ms.ToArray ();
                             displayImage (userImage);
                         }
                     }
                 }
                 AndroidData.imageFileName = filename;
             }
         }
         break;
     case PICCY:
         if (resultCode == Result.Ok) {
             string filename = getRealPathFromUri (data.Data);
             using (Bitmap bmp = BitmapFactory.DecodeFile(filename)) {
                 if (bmp != null) {
                     using (MemoryStream ms = new MemoryStream ()) {
                         bmp.Compress (Bitmap.CompressFormat.Jpeg, 80, ms);
                         if (userImage == null)
                             userImage = new byte[ms.Length];
                         userImage = ms.ToArray ();
                         displayImage (userImage);
                     }
                 }
             }
             AndroidData.imageFileName = filename;
         }
         break;
     case NEXT:
         username.Text = data.GetStringExtra ("username");
         email.Text = data.GetStringExtra ("email");
         password.Text = verify.Text = data.GetStringExtra ("password");
         userImage = data.GetByteArrayExtra ("image");
         displayImage (userImage);
         break;
     }
 }
			public override void OnReceive(Context context, Intent intent)
			{
				this.parent.logger.d (OAuthClientHandlerService.LOG_TAG, "recieved event, data: " + intent.GetStringExtra ("url"), null);
				string data = intent.GetStringExtra ("url");
				if ("NOT_FINISHED".Equals (data)) {
					OAuthResult oauthResult = new OAuthResult (OAuthResult.ResultCode.Failed, new Exception ("NOT_FINISHED"));
					this.parent.tcs.TrySetResult (oauthResult);
				} else if ("CANCELLED".Equals (data)) {
					OAuthResult oauthResult = new OAuthResult (OAuthResult.ResultCode.Cancelled, new Exception ("USER_CANCELLED"));
					this.parent.tcs.TrySetResult (oauthResult);
				} else {
					this.parent.appContext.UnregisterReceiver (this.parent.receiver);
					OnSuccess (new Uri (data), this.parent.tcs);
				}
			}
示例#28
0
            public override void OnReceive(Context context, Intent intent)
            {
                if (intent.Action == MSG_BCAST)
                {
                    string fromEmail = intent.GetStringExtra("fromEmail");
                    string fromName = intent.GetStringExtra("fromName");
                    if (fromEmail.Equals(toEmail))
                    {
                        string msgContent = intent.GetStringExtra("message");
                        msgAdapter.Add(fromName+ ":  "+msgContent);
                        
                    }

                }
            }
示例#29
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper;

            serviceHelper.Logger.Log("Sensus service received start command (startId=" + startId + ").", LoggingLevel.Normal, GetType());

            serviceHelper.MainActivityWillBeDisplayed = intent.GetBooleanExtra(AndroidSensusServiceHelper.MAIN_ACTIVITY_WILL_BE_DISPLAYED, false);

            // the service can be stopped without destroying the service object. in such cases, 
            // subsequent calls to start the service will not call OnCreate. therefore, it's 
            // important that any code called here is okay to call multiple times, even if the 
            // service is running. calling this when the service is running can happen because 
            // sensus receives a signal on device boot and for any callback alarms that are 
            // requested. furthermore, all calls here should be nonblocking / async so we don't 
            // tie up the UI thread.

            serviceHelper.StartAsync(() =>
                {
                    if (intent.GetBooleanExtra(AndroidSensusServiceHelper.SENSUS_CALLBACK_KEY, false))
                    {
                        string callbackId = intent.GetStringExtra(AndroidSensusServiceHelper.SENSUS_CALLBACK_ID_KEY);
                        if (callbackId != null)
                        {
                            bool repeating = intent.GetBooleanExtra(AndroidSensusServiceHelper.SENSUS_CALLBACK_REPEATING_KEY, false);
                            serviceHelper.RaiseCallbackAsync(callbackId, repeating, true);
                        }
                    }
                });

            return StartCommandResult.RedeliverIntent;
        }
示例#30
0
        protected override void OnMessage (Context context, Intent intent)
        {
            //Push Notification arrived - print out the keys/values
            Intent received = new Intent (context, typeof(RecievedPush));
            string pushMessage = intent.GetStringExtra ("message");
            received.AddFlags (ActivityFlags.ReorderToFront);
            received.AddFlags (ActivityFlags.NewTask);
            received.PutExtra ("pushedMessage", pushMessage);
            if (intent == null || intent.Extras == null) {
                received.PutExtras (intent.Extras);
                foreach (var key in intent.Extras.KeySet()) {
                    Console.WriteLine ("Key: {0}, Value: {1}");
                }
            }
            PendingIntent notificationLaunch = PendingIntent.GetActivity (context, 1000, received, PendingIntentFlags.CancelCurrent );
            NotificationManager manager = (NotificationManager)GetSystemService (Context.NotificationService);
            NotificationCompat.Builder builder = new NotificationCompat.Builder (context);
            builder.SetContentText (pushMessage);
            builder.SetContentIntent ( notificationLaunch);
            builder.SetContentTitle ("New Message");
            builder.SetSmallIcon (Resource.Drawable.ic_action_chat);
            builder.SetStyle ( new NotificationCompat.InboxStyle());
            builder.SetSound (RingtoneManager.GetDefaultUri (RingtoneType.Notification));
            builder.SetVibrate (new long[] { 500, 300, 100, 1000, 300, 300, 300 ,300 });
            manager.Notify (1000, builder.Build ());

            Buddy.RecordNotificationReceived(intent);
         
        }
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            _serviceHelper.Logger.Log("Sensus service received start command (startId=" + startId + ").", LoggingLevel.Debug, GetType());

            _serviceHelper.MainActivityWillBeSet = intent.GetBooleanExtra(AndroidSensusServiceHelper.MAIN_ACTIVITY_WILL_BE_SET, false);

            // the service can be stopped without destroying the service object. in such cases,
            // subsequent calls to start the service will not call OnCreate, which is why the
            // following code needs to run here -- e.g., starting the helper object and displaying
            // the notification. therefore, it's important that any code called here is
            // okay to call multiple times, even if the service is running. calling this when
            // the service is running can happen because sensus receives a signal on device
            // boot and for any callback alarms that are requested. furthermore, all calls here
            // should be nonblocking / async so we don't tie up the UI thread.

            _serviceHelper.StartAsync(() =>
                {
                    if (intent.GetBooleanExtra(AndroidSensusServiceHelper.SENSUS_CALLBACK_KEY, false))
                    {
                        string callbackId = intent.GetStringExtra(AndroidSensusServiceHelper.SENSUS_CALLBACK_ID_KEY);
                        if (callbackId != null)
                        {
                            bool repeating = intent.GetBooleanExtra(AndroidSensusServiceHelper.SENSUS_CALLBACK_REPEATING_KEY, false);
                            _serviceHelper.RaiseCallbackAsync(callbackId, repeating, true);
                        }
                    }
                });

            return StartCommandResult.RedeliverIntent;
        }
 public void RecordNotificationReceived(Intent message)
 {
     var id = message.GetStringExtra(PlatformAccess.BuddyPushKey);
     if (!String.IsNullOrEmpty(id)) {
         PlatformAccess.Current.OnNotificationReceived(id);
     }
 }
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            string cogida1 = intent.GetStringExtra("querry1");
            string cogida2 = intent.GetStringExtra("querry2");
            string cogida3 = intent.GetStringExtra("querry3");
            string cogida4 = intent.GetStringExtra("querry4");
            string cogida5 = intent.GetStringExtra("querry5");

            if (cogida1 == "si")
            {
                playeroffline.gettearinstancia().playpause.CallOnClick();
                // clasesettings.guardarsetting("cquerry", "playpause()");
            }
            else
            if (cogida2 == "si")
            {
                playeroffline.gettearinstancia().siguiente.CallOnClick();
                //  clasesettings.guardarsetting("cquerry", "siguiente()");
            }
            else
            if (cogida3 == "si")
            {
                playeroffline.gettearinstancia().anterior.CallOnClick();
                //  clasesettings.guardarsetting("cquerry", "anterior()");
            }
            else
            if (cogida4 == "si")
            {
                playeroffline.gettearinstancia().adelantar.CallOnClick();
                /// clasesettings.guardarsetting("cquerry", "adelantar()");
            }
            else
            if (cogida5 == "si")
            {
                playeroffline.gettearinstancia().atrazar.CallOnClick();
                ///  clasesettings.guardarsetting("cquerry", "atrazar()");
            }



            this.StopSelf();
        }
示例#34
0
        protected override async void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == AccountRequestCode &&
                resultCode == Result.Ok)
            {
                _accountName = data.GetStringExtra(AccountManager.KeyAccountName);
                await RefreshAccountDetails();
            }
        }
示例#35
0
        protected override void OnNewIntent(Android.Content.Intent intent)
        {
            Intent = intent;
            mQuery = intent.GetStringExtra(SearchManager.Query);

            var title = GetString(Resource.String.title_search_query, mQuery);

            ActivityHelper.SetActionBarTitle(new Java.Lang.String(title));

            mTabHost.CurrentTab = 0;

            mSessionsFragment.ReloadFromArguments(GetSessionsFragmentArguments());
            mVendorsFragment.ReloadFromArguments(GetVendorsFragmentArguments());
        }
示例#36
0
        protected override void OnNewIntent(Android.Content.Intent intent)
        {
            base.OnNewIntent(intent);

            // Get the barcode options from the intent
            var barcodeFormat = ZXing.BarcodeFormat.QR_CODE;

            if (intent.HasExtra("FORMAT"))
            {
                System.Enum.TryParse <ZXing.BarcodeFormat> (intent.GetStringExtra("FORMAT"), out barcodeFormat);
            }

            var barcodeValue = string.Empty;

            if (intent.HasExtra("VALUE"))
            {
                barcodeValue = intent.GetStringExtra("VALUE") ?? string.Empty;
            }

            var barcodeUrl = string.Empty;

            if (intent.HasExtra("URL"))
            {
                barcodeUrl = intent.GetStringExtra("URL") ?? string.Empty;
            }

            // Can set from a URL or generate from a format/value
            if (!string.IsNullOrEmpty(barcodeUrl))
            {
                SetBarcode(barcodeUrl);
            }
            else if (!string.IsNullOrEmpty(barcodeValue))
            {
                SetBarcode(barcodeFormat, barcodeValue);
            }
        }
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            string ipadress = intent.GetStringExtra("ipadre");
            string cogida1  = intent.GetStringExtra("querry1");
            string cogida2  = intent.GetStringExtra("querry2");
            string cogida3  = intent.GetStringExtra("querry3");
            string cogida4  = intent.GetStringExtra("querry4");
            string cogida5  = intent.GetStringExtra("querry5");

            if (cogida1 == "si")
            {
                Mainmenu.gettearinstancia().RunOnUiThread(() =>
                {
                    Mainmenu.gettearinstancia().play.CallOnClick();
                });
            }
            else
            if (cogida2 == "si")
            {
                Mainmenu.gettearinstancia().RunOnUiThread(() =>
                {
                    Mainmenu.gettearinstancia().adelante.CallOnClick();
                });
            }
            else
            if (cogida3 == "si")
            {
                Mainmenu.gettearinstancia().RunOnUiThread(() =>
                {
                    Mainmenu.gettearinstancia().atras.CallOnClick();
                });
            }
            else
            if (cogida4 == "si")
            {
                Mainmenu.gettearinstancia().RunOnUiThread(() =>
                {
                    Mainmenu.gettearinstancia().adelantar.CallOnClick();
                });
            }
            else
            if (cogida5 == "si")
            {
                Mainmenu.gettearinstancia().RunOnUiThread(() =>
                {
                    Mainmenu.gettearinstancia().atrazar.CallOnClick();
                });
            }



            this.StopSelf();
        }
        protected override async void OnHandleIntent(Android.Content.Intent intent)
        {
            try
            {
                if (!Boolean.Parse(Java.Lang.JavaSystem.GetProperty("com.mobileiron.wrapped", "false")) &&
                    !this.PackageName.Equals(PackageManager.GetPermissionInfo("com.mobileiron.CONFIG_PERMISSION", 0).PackageName))
                {
                    Log.Debug(TAG, "Refusing intent as we don't own our permission?!");
                }
            }

            catch (PackageManager.NameNotFoundException ex)
            {
                Log.Debug(TAG, ex.Message + " " + "Refusing intent as we can't find our permission?!");
                return;
            }

            if ("com.mobileiron.HANDLE_CONFIG".Equals(intent.Action))
            {
                Log.Debug(TAG, "Received intent : " + intent + " from package " + intent.GetStringExtra("packageName"));

                Bundle config = intent.GetBundleExtra("config");

                if (config != null)
                {
                    Log.Debug(TAG, "Config Received");
                    foreach (var key in config.KeySet())
                    {
                        if (key == "alias")
                        {
                            Log.Debug(TAG, "Alias = " + config.GetString(key));
                        }
                    }
                    MessagingCenter.Send <IMobileIron>(this, "ConfigParsed");

                    HttpClient client = new HttpClient(new NativeMessageHandler {
                        DisableCaching = true
                    });
                    var response = await client.GetAsync("https://teamspace.slb.com/sites/ingwellmaps/_vti_bin/listdata.svc");

                    GalaSoft.MvvmLight.Messaging.Messenger.Default.Send(new NotificationMessage(await response.Content.ReadAsStringAsync()));
                }
            }
        }
示例#39
0
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            netWorkHelper = new NetWorkHelper();
            var ip = intent.GetStringExtra("ip");

            try {
                NetWorkHelper.Connect(ip);
            }
            catch (Exception ex)
            {
                Log.Debug("NetworkService", "Connection error:" + ex.Message);
            }

            if (NetWorkHelper.IsConnected)
            {
                NetWorkHelper.Send("I connected with you!");
            }

            // Return the correct StartCommandResult for the type of service you are building
            return(StartCommandResult.NotSticky);
        }
示例#40
0
            public override void OnReceive(Context context, Android.Content.Intent intent)
            {
                if (intent.Action == AppConst.rxIntentName)                                                   // We've received data
                {
                    string s = intent.GetStringExtra(BundleConst.bundleCmdTag);
                    if (s == BundleConst.bundleDataTag)
                    {
                        int i = intent.GetIntExtra(BundleConst.bundleValTag, 0);

                        mainActivity.UpdateUI(i);
                    }
                    else if (s == BundleConst.bundleStatusTag)                                                    // We've received a status update
                    {
                        activityState = (AppConst.ActivityState)intent.GetIntExtra(BundleConst.bundleValTag, 0);
                        switch (activityState)
                        {
                        case AppConst.ActivityState.idle:
                            mainActivity.DisableButtons();
                            break;

                        case AppConst.ActivityState.connected:
                            mainActivity.DisableButtons();
                            break;

                        case AppConst.ActivityState.synced:
                            mainActivity.EnableButtons();
                            connectionErrors = 0;
                            break;

                        case AppConst.ActivityState.error:
                            mainActivity.DisableButtons();
                            connectionErrors += 1;
                            mainActivity.ScanOrConnect();                                                        // Attempt reconnection
                            break;
                        }
                        mainActivity.CommunicateState(activityState);
                    }
                }
            }
示例#41
0
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            string mode = intent.GetStringExtra("mode");

            string   alarmAdi      = intent.GetStringExtra("alarmAdi");
            TimeSpan alarmSaati    = TimeSpan.Parse(intent.GetStringExtra("alarmSaati"));
            int      alarmInterval = int.Parse(intent.GetStringExtra("interval"));
            int      alarmVolume   = int.Parse(intent.GetStringExtra("volume"));
            int      alarmPresses  = int.Parse(intent.GetStringExtra("presses"));
            int      alarmShakes   = int.Parse(intent.GetStringExtra("shakes"));
            string   week          = intent.GetStringExtra("week");

            intent.RemoveExtra("alarmAdi");
            intent.RemoveExtra("alarmSaati");
            intent.RemoveExtra("interval");
            intent.RemoveExtra("volume");
            intent.RemoveExtra("presses");
            intent.RemoveExtra("shakes");
            intent.RemoveExtra("mode");
            intent.RemoveExtra("week");

            int today = (int)DateTime.Today.DayOfWeek;

            List <int> alarmDays = new List <int>();

            // sunday - 0, monday - 1 ... saturday - 6

            if (week.Contains("pzr"))
            {
                alarmDays.Add((int)DayOfWeek.Sunday);
            }

            if (week.Contains("pzt"))
            {
                alarmDays.Add((int)DayOfWeek.Monday);
            }

            if (week.Contains("sal"))
            {
                alarmDays.Add((int)DayOfWeek.Tuesday);
            }

            if (week.Contains("crs"))
            {
                alarmDays.Add((int)DayOfWeek.Wednesday);
            }

            if (week.Contains("prs"))
            {
                alarmDays.Add((int)DayOfWeek.Thursday);
            }

            if (week.Contains("cum"))
            {
                alarmDays.Add((int)DayOfWeek.Friday);
            }

            if (week.Contains("cmt"))
            {
                alarmDays.Add((int)DayOfWeek.Saturday);
            }

            List <long> millis = new List <long>();

            if (alarmDays.Count == 0)
            {
                long millisecondsToWait = Convert.ToInt64(alarmSaati.TotalMilliseconds
                                                          - DateTime.Now.TimeOfDay.TotalMilliseconds);
                if (millisecondsToWait <= 0)
                {
                    millisecondsToWait += 24 * 3600 * 1000;
                }

                millis.Add(millisecondsToWait);
            }
            else
            {
                for (int i = 0; i < alarmDays.Count; i++)
                {
                    int  diff = alarmDays[i] - today;
                    long millisecondsToWait = Convert.ToInt64(alarmSaati.TotalMilliseconds
                                                              - DateTime.Now.TimeOfDay.TotalMilliseconds);
                    millisecondsToWait += diff * 24 * 3600 * 1000; // add days diff
                    if (millisecondsToWait < 0)
                    {
                        millisecondsToWait += 7 * 24 * 3600 * 1000;
                    }

                    millis.Add(millisecondsToWait);
                }
            }

            if (mode.Equals("first"))
            {
                long millisecondsToWait = millis.Min(time => time);
                //int index = millis.FindIndex((item) => (item == millisecondsToWait));
                DateTime alarmDay = DateTime.Now + TimeSpan.FromMilliseconds(millisecondsToWait);

                DayOfWeek dow = alarmDay.DayOfWeek;
                string    day = "";
                switch (dow)
                {
                case DayOfWeek.Monday:
                    day = "pzt";
                    break;

                case DayOfWeek.Tuesday:
                    day = "sal";
                    break;

                case DayOfWeek.Wednesday:
                    day = "crs";
                    break;

                case DayOfWeek.Thursday:
                    day = "prs";
                    break;

                case DayOfWeek.Friday:
                    day = "cum";
                    break;

                case DayOfWeek.Saturday:
                    day = "cmt";
                    break;

                case DayOfWeek.Sunday:
                    day = "pzr";
                    break;
                }

                var reminderIntent = new Intent(Forms.Context, typeof(ReminderReceiver)); //takvim denetimi
                reminderIntent.PutExtra("title", alarmAdi);
                reminderIntent.PutExtra("message", "boþ: " + alarmSaati.ToString(@"hh\:mm") + ", " + day);
                reminderIntent.PutExtra("alarmSaati", alarmSaati.ToString());
                // unique id
                string _id             = alarmAdi + alarmSaati.ToString(@"hh\:mm");
                int    _alarmId        = _id.GetHashCode();
                var    reminderPending = PendingIntent.GetBroadcast(Forms.Context, _alarmId, reminderIntent, PendingIntentFlags.UpdateCurrent);

                //      var alarmManager = (AlarmManager)Forms.Context.GetSystemService(Context.AlarmService);
                _alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime(), reminderPending);

                var alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
                alarmIntent.PutExtra("alarmSaati", alarmSaati.ToString());
                alarmIntent.PutExtra("alarmAdi", alarmAdi);
                alarmIntent.PutExtra("interval", alarmInterval.ToString());
                alarmIntent.PutExtra("volume", alarmVolume.ToString());
                alarmIntent.PutExtra("presses", alarmPresses.ToString());
                alarmIntent.PutExtra("shakes", alarmShakes.ToString());

                var alarmPending = PendingIntent.GetBroadcast(Forms.Context, _alarmId, alarmIntent, PendingIntentFlags.UpdateCurrent);
                _alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + millisecondsToWait, alarmPending);
            }
            else
            {
                alarmSaati = DateTime.Now.TimeOfDay.Add(TimeSpan.FromMilliseconds(alarmInterval * 60 * 1000));
                var reminderIntent = new Intent(Forms.Context, typeof(ReminderReceiver));
                reminderIntent.PutExtra("title", alarmAdi + "()");
                reminderIntent.PutExtra("message", "boþ: " + alarmSaati.ToString(@"hh\:mm"));
                reminderIntent.PutExtra("alarmSaati", alarmSaati.ToString());

                string _id      = alarmAdi;// + alarmTime.ToString(@"hh\:mm");
                int    _alarmId = _id.GetHashCode();

                var reminderPending = PendingIntent.GetBroadcast(Forms.Context, _alarmId, reminderIntent, PendingIntentFlags.UpdateCurrent);

                var alarmManager = (AlarmManager)Forms.Context.GetSystemService(Context.AlarmService);
                _alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime(), reminderPending);

                var alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
                alarmIntent.PutExtra("alarmSaati", alarmSaati.ToString());
                alarmIntent.PutExtra("alarmAdi", alarmAdi);
                alarmIntent.PutExtra("interval", alarmInterval.ToString());
                alarmIntent.PutExtra("volume", alarmVolume.ToString());
                alarmIntent.PutExtra("presses", alarmPresses.ToString());
                alarmIntent.PutExtra("shakes", alarmShakes.ToString());
                long millisecondsToWait = alarmInterval * 60 * 1000;

                var alarmPending = PendingIntent.GetBroadcast(Forms.Context, _alarmId, alarmIntent, PendingIntentFlags.UpdateCurrent);
                _alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + millisecondsToWait, alarmPending);
            }
        }