Example #1
1
		protected override void OnNewIntent(Intent intent)
		{
			if (_inWriteMode)
			{
				_inWriteMode = false;
				var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

				if (tag == null)
				{
					return;
				}

				// These next few lines will create a payload (consisting of a string)
				// and a mimetype. NFC record are arrays of bytes. 
				var message = _inputText.Text += " " + DateTime.Now.ToString("HH:mm:ss dd/M/yyyy");
				_outputText.Text = message;
				var payload = Encoding.ASCII.GetBytes(message);
				var mimeBytes = Encoding.ASCII.GetBytes(ViewIsolationType);
				var isolationRecord = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
				var ndefMessage = new NdefMessage(new[] { isolationRecord });

				TryAndFormatTagWithMessage(tag, ndefMessage);  
				if (!TryAndWriteToTag(tag, ndefMessage))
				{
					// Maybe the write couldn't happen because the tag wasn't formatted?
					TryAndFormatTagWithMessage(tag, ndefMessage);                    
				}
			}
		}
        public override void OnActivityResult(int requestCode, int resultCode, Android.Content.Intent data)
        {
            mProgressDialog.Hide();

            // retrieve the error code, if available
            int errorCode = -1;

            if (data != null)
            {
                errorCode = data.GetIntExtra(WalletConstants.ExtraErrorCode, -1);
            }

            switch (requestCode)
            {
            case REQUEST_CODE_RESOLVE_ERR:
                if (resultCode == (int)Result.Ok)
                {
                    mGoogleApiClient.Connect();
                }
                else
                {
                    handleUnrecoverableGoogleWalletError(errorCode);
                }
                break;

            case REQUEST_CODE_RESOLVE_LOAD_FULL_WALLET:
                switch (resultCode)
                {
                case (int)Result.Ok:
                    if (data.HasExtra(WalletConstants.ExtraFullWallet))
                    {
                        FullWallet fullWallet =
                            data.GetParcelableExtra(WalletConstants.ExtraFullWallet).JavaCast <FullWallet> ();
                        // the full wallet can now be used to process the customer's payment
                        // send the wallet info up to server to process, and to get the result
                        // for sending a transaction status
                        fetchTransactionStatus(fullWallet);
                    }
                    else if (data.HasExtra(WalletConstants.ExtraMaskedWallet))
                    {
                        // re-launch the activity with new masked wallet information
                        mMaskedWallet = data.GetParcelableExtra(WalletConstants.ExtraMaskedWallet).JavaCast <MaskedWallet> ();
                        mActivityLaunchIntent.PutExtra(Constants.EXTRA_MASKED_WALLET, mMaskedWallet);

                        StartActivity(mActivityLaunchIntent);
                    }
                    break;

                case (int)Result.Canceled:
                    // nothing to do here
                    break;

                default:
                    handleError(errorCode);
                    break;
                }
                break;
            }
        }
Example #3
0
        public override IBinder OnBind(Intent intent)
        {
            if (intent.GetParcelableExtra("MESSENGER") != null) {
             this.outMessenger = (Messenger) intent.GetParcelableExtra("MESSENGER");
            }

            return inMessenger.Binder;
        }
		protected override void OnActivityResult(int requestCode, Android.App.Result resultCode, Intent data)
		{
			base.OnActivityResult(requestCode, resultCode, data);

			switch (requestCode)
			{
				case MaskedWalletRequest:
					PerformFullWalletRequest((MaskedWallet)data.GetParcelableExtra(WalletConstants.ExtraMaskedWallet));
					break;

				case FullWalletRequest:
					PerformJudoPayment((FullWallet)data.GetParcelableExtra(WalletConstants.ExtraFullWallet));
					break;
			}
		}
        /// <summary>
        /// This method is called when an NFC tag is discovered by the application.
        /// </summary>
        /// <param name="intent"></param>
        protected override void OnNewIntent(Intent intent)
        {
            if (_inWriteMode)
            {
                _inWriteMode = false;
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (tag == null)
                {
                    return;
                }

                // These next few lines will create a payload (consisting of a string)
                // and a mimetype. NFC record are arrays of bytes.
                var payload = Encoding.ASCII.GetBytes(GetRandomHominid());
                var mimeBytes = Encoding.ASCII.GetBytes(ViewApeMimeType);
                var apeRecord = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
                var ndefMessage = new NdefMessage(new[] { apeRecord });

                if (!TryAndWriteToTag(tag, ndefMessage))
                {
                    // Maybe the write couldn't happen because the tag wasn't formatted?
                    TryAndFormatTagWithMessage(tag, ndefMessage);
                }
            }
        }
        public override void OnCreate (Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);
        
            if (savedInstanceState != null) {
                mRetryCounter = savedInstanceState.GetInt (KEY_RETRY_COUNTER);
                mRetryLoadFullWalletCount = savedInstanceState.GetInt (KEY_RETRY_FULL_WALLET_COUNTER);
                mHandleFullWalletWhenReady =
                    savedInstanceState.GetBoolean (KEY_HANDLE_FULL_WALLET_WHEN_READY);
            }
            mActivityLaunchIntent = Activity.Intent;
            mItemId = mActivityLaunchIntent.GetIntExtra (Constants.EXTRA_ITEM_ID, 0);
            mMaskedWallet = mActivityLaunchIntent.GetParcelableExtra (Constants.EXTRA_MASKED_WALLET).JavaCast<MaskedWallet> ();

            var accountName = ((BikestoreApplication) Activity.Application).AccountName;

            // Set up an API client;
            mGoogleApiClient = new GoogleApiClient.Builder (Activity)
                .AddConnectionCallbacks (this)
                .AddOnConnectionFailedListener (this)
                .SetAccountName (accountName)
                .AddApi (WalletClass.API, new WalletClass.WalletOptions.Builder ()
                    .SetEnvironment (Constants.WALLET_ENVIRONMENT)
                    .SetTheme (WalletConstants.ThemeLight)
                    .Build ())
                .Build ();

            mRetryHandler = new RetryHandler (this);
        }
		protected override void OnHandleIntent (Intent intent)
		{
			Log.Debug (TAG, "onHandleIntent(intent=" + intent.ToString () + ")");

			ResultReceiver receiver = (ResultReceiver)intent.GetParcelableExtra (EXTRA_STATUS_RECEIVER);
			if (receiver != null)
				receiver.Send (StatusRunning, Bundle.Empty);
	
			Context context = this;
			var prefs = GetSharedPreferences (Prefs.IOSCHED_SYNC, FileCreationMode.Private);
			int localVersion = prefs.GetInt (Prefs.LOCAL_VERSION, VERSION_NONE);
	
			try {
				// Bulk of sync work, performed by executing several fetches from
				// local and online sources.
	
				long startLocal = Java.Lang.JavaSystem.CurrentTimeMillis ();
				bool localParse = localVersion < VERSION_CURRENT;
				Log.Debug (TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT);
				if (localParse) {
					// Load static local data
					mLocalExecutor.Execute (Resource.Xml.blocks, new LocalBlocksHandler ());
					mLocalExecutor.Execute (Resource.Xml.rooms, new LocalRoomsHandler ());
					mLocalExecutor.Execute (Resource.Xml.tracks, new LocalTracksHandler ());
					mLocalExecutor.Execute (Resource.Xml.search_suggest, new LocalSearchSuggestHandler ());
					mLocalExecutor.Execute (Resource.Xml.sessions, new LocalSessionsHandler ());
	
					// Parse values from local cache first, since spreadsheet copy
					// or network might be down.
//	                mLocalExecutor.execute(context, "cache-sessions.xml", new RemoteSessionsHandler());
//	                mLocalExecutor.execute(context, "cache-speakers.xml", new RemoteSpeakersHandler());
//	                mLocalExecutor.execute(context, "cache-vendors.xml", new RemoteVendorsHandler());
	
					// Save local parsed version
					prefs.Edit ().PutInt (Prefs.LOCAL_VERSION, VERSION_CURRENT).Commit ();
				}
	            
				Log.Debug (TAG, "local sync took " + (Java.Lang.JavaSystem.CurrentTimeMillis () - startLocal) + "ms");
	
				// Always hit remote spreadsheet for any updates
				long startRemote = Java.Lang.JavaSystem.CurrentTimeMillis ();
//		        mRemoteExecutor.executeGet(WORKSHEETS_URL, new RemoteWorksheetsHandler(mRemoteExecutor));
				Log.Debug (TAG, "remote sync took " + (Java.Lang.JavaSystem.CurrentTimeMillis () - startRemote) + "ms");
			
			} catch (Exception e) {
				Log.Error (TAG, "Problem while syncing", e);
		
				if (receiver != null) {
					// Pass back error to surface listener
					Bundle bundle = new Bundle ();
					bundle.PutString (Intent.ExtraText, e.ToString ());
					receiver.Send (StatusError, bundle);
				}        
			}

			// Announce success to any surface listener
			Log.Debug (TAG, "sync finished");
			if (receiver != null)
				receiver.Send (StatusFinished, Bundle.Empty);
		}
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;

             				// When discovery finds a device
            if (action == BluetoothDevice.ActionFound)
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

                Console.WriteLine(String.Format("Bluetooth Device: {0}", device.Name));

                if(_location == null)
                {
                    throw new NullReferenceException("Location in the Reciever is NULL");
                }

                BTSearchResult result = new BTSearchResult(_location);

                //fill out result.

                _results.Add(result);

                // If it's already paired, skip it, because it's been listed already
                if (device.BondState != Bond.Bonded)
                {

                }
                // When discovery is finished, change the Activity title
            }
        }
        public override void OnReceive(Context context, Intent intent)
        {
            var action = intent.Action;

            if (WifiP2pManager.WifiP2pStateChangedAction.Equals(action))
            {
                // UI update to indicate wifi p2p status.
                var state = intent.GetIntExtra(WifiP2pManager.ExtraWifiState, -1);
                if (state == (int) WifiP2pState.Enabled)
                    // Wifi Direct mode is enabled
                    _activity.IsWifiP2PEnabled = true;
                else
                {
                    _activity.IsWifiP2PEnabled = false;
                    _activity.ResetData();
                }
                Log.Debug(WiFiDirectActivity.Tag, "P2P state changed - " + state);
            }
            else if (WifiP2pManager.WifiP2pPeersChangedAction.Equals(action))
            {
                // request available peers from the wifi p2p manager. This is an
                // asynchronous call and the calling activity is notified with a
                // callback on PeerListListener.onPeersAvailable()
                if (_manager != null)
                {
                    _manager.RequestPeers(_channel,
                                          _activity.FragmentManager.FindFragmentById<DeviceListFragment>(Resource.Id.frag_list));
                }
                Log.Debug(WiFiDirectActivity.Tag, "P2P peers changed");
            }
            else if (WifiP2pManager.WifiP2pConnectionChangedAction.Equals(action))
            {
                if (_manager == null)
                    return;

                var networkInfo = (NetworkInfo) intent.GetParcelableExtra(WifiP2pManager.ExtraNetworkInfo);

                if (networkInfo.IsConnected)
                {
                    // we are connected with the other device, request connection
                    // info to find group owner IP

                    var fragment =
                        _activity.FragmentManager.FindFragmentById<DeviceDetailFragment>(Resource.Id.frag_detail);
                    _manager.RequestConnectionInfo(_channel, fragment);
                }
                else
                {
                    // It's a disconnect
                    _activity.ResetData();
                }
            }
            else if (WifiP2pManager.WifiP2pThisDeviceChangedAction.Equals(action))
            {
                var fragment =
                        _activity.FragmentManager.FindFragmentById<DeviceListFragment>(Resource.Id.frag_list);
                fragment.UpdateThisDevice((WifiP2pDevice)intent.GetParcelableExtra(WifiP2pManager.ExtraWifiP2pDevice));
            }
        }
 public override void OnReceive(global::Android.Content.Context context, Intent intent)
 {
     if (DEVICE_FOUND != null && intent != null && intent.Action == BluetoothDevice.ActionFound)
     {
         BluetoothDevice device = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice) as BluetoothDevice;
         DEVICE_FOUND(this, new BluetoothDeviceProximityDatum(DateTimeOffset.UtcNow, device.Name, device.Address));
     }
 }
 public void OnReceive(Context context, Intent intent)
 {
     if(BluetoothDevice.ActionFound == intent.Action)
     {
         var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
         var rssi = intent.GetShortExtra(BluetoothDevice.ExtraRssi, 0);
         Toast.MakeText(context, device.Name, ToastLength.Long).Show();
     }
 }
            public override void OnReceive (Context context, Intent intent)
            {
                var extraDevice = intent.GetParcelableExtra(UsbManager.ExtraDevice) as UsbDevice;
                if (device.DeviceName != extraDevice.DeviceName)
                    return;

                var permissionGranted = intent.GetBooleanExtra (UsbManager.ExtraPermissionGranted, false);
                observer.OnNext (permissionGranted);
                observer.OnCompleted ();
            }
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (resultCode == Result.Ok)
            {
                Core core = Core.GetCore();
                AppConfig config = core.GetConfig();
                Android.Net.Uri ring = (Android.Net.Uri)data.GetParcelableExtra(RingtoneManager.ExtraRingtonePickedUri);

                DependencyService.Get<iRingTones>().SetSelectedRingTone(ring.ToString());
            }
        }
        public override void OnReceive(Context context, Intent intent)
        {
            Console.Out.WriteLine("HELPS: Spawning Notification");
            if (!SettingService.notificationsEnbabled())
                return;

            var notificationManager =
                (NotificationManager) context.GetSystemService(Context.NotificationService);

            var notification = (Notification) intent.GetParcelableExtra(NOTIFICATION);
            var id = intent.GetIntExtra(NOTIFICATION_ID, 0);
            notificationManager.Notify(id, notification);
        }
Example #15
0
        public override void OnReceive(Context context, Intent intent)
        {
            //Console.WriteLine("[{0}] Received result: {1}", TAG, ResultCode);
            if (ResultCode != Result.Ok) {
                // A foreground activity cancelled the broadcast
                return;
            }

            int requestCode = intent.GetIntExtra("REQUEST_CODE", 0);
            Notification notification = (Notification)intent.GetParcelableExtra("NOTIFICATION");

            NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
            notificationManager.Notify(requestCode, notification);
        }
        protected override void OnHandleIntent(Intent intent)
        {
            string errorMessage = "";
            // Get the location passed to this service through an extra.
            var location = intent.GetParcelableExtra(Constants.LOCATION_DATA_EXTRA).JavaCast<Location>();
            var geocoder = new Geocoder(this, Java.Util.Locale.Default);
            IList<Address> addresses = null;
            try
            {
                // In this sample, get just a single address.
                addresses = geocoder.GetFromLocation(location.Latitude, location.Longitude, 1);
            }
            catch (Java.IO.IOException ioException)
            {
                // Catch network or other I/O problems.
                errorMessage = "service not available";
                Console.WriteLine("{0} {1}", errorMessage, ioException.ToString());
            }
            catch (Java.Lang.IllegalArgumentException illegalArgumentException)
            {
                // Catch invalid latitude or longitude values.
                errorMessage = "invalid lat long used. " + "Latitude = " + location.Latitude + ", Longitude = " + location.Longitude;
                Console.WriteLine("{0} {1}", errorMessage, illegalArgumentException.ToString());
            }

            // Handle case where no address was found.
            if (addresses == null || addresses.Count == 0)
            {
                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = "no address found";
                    Console.WriteLine(errorMessage);
                }
                DeliverResultToReceiver(GeocodingResult.Failure, errorMessage);
            }
            else
            {
                Address address = addresses[0];
                var addressFragments = new List<string>();
                // Fetch the address lines using getAddressLine,
                // join them, and send them to the thread.
                for (int i = 0; i < address.MaxAddressLineIndex; i++)
                {
                    addressFragments.Add(address.GetAddressLine(i));
                }
                Console.WriteLine("address_found");
                DeliverResultToReceiver(GeocodingResult.Success, addressFragments);
            }
        }
        protected override void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent data)
        {
            if (requestCode != APP_REQUEST_CODE)
            {
                base.OnActivityResult(requestCode, resultCode, data);

                Finish();
                return;
            }

            var result = (IAKAccountKitLoginResult)data?.GetParcelableExtra(AKAccountKitLoginResult.ResultKey);

            Completed?.Invoke(result);

            Finish();
        }
        protected override void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);


            if (requestCode != APP_REQUEST_CODE)
            {
                return;
            }

            var jobj = data.GetParcelableExtra(AccountKitLoginResult.ResultKey);
            IAccountKitLoginResult loginResult = Android.Runtime.Extensions.JavaCast <IAccountKitLoginResult>(jobj);
            var toastMessage = "Hello, AccountKit.";

            if (loginResult.Error != null)
            {
                toastMessage = loginResult.Error.ErrorType.Message;

                //ShowErrorActivity(loginResult.Error);
            }
            else if (loginResult.WasCancelled())
            {
                toastMessage = "Login Cancelled";
            }
            else
            {
                if (loginResult.AccessToken != null)
                {
                    toastMessage = "Success:" + loginResult.AccessToken.AccountId;
                }
                else
                {
                    toastMessage = string.Format(
                        "Success:{0}...",
                        loginResult.AuthorizationCode.Substring(0, 10));
                }

                GetCurrentAccount();
            }

            // Surface the result to your user in an appropriate way.
            Toast.MakeText(
                this,
                toastMessage,
                ToastLength.Long)
            .Show();
        }
Example #19
0
        public override void OnReceive(Context context, Intent intent)
        {
            sqlite3_shutdown();
            SqliteConnection.SetConfig(SQLiteConfig.Serialized);
            sqlite3_initialize();

            // If you got a location extra, use it
            Location loc = (Location)intent.GetParcelableExtra(LocationManager.KeyLocationChanged);
            if (loc != null) {
                OnLocationReceived(context, loc);
                return;
            }
            // If you get here, something else has happened
            if (intent.HasExtra(LocationManager.KeyProviderEnabled)) {
                bool enabled = intent.GetBooleanExtra(LocationManager.KeyProviderEnabled, false);
                OnProviderEnabledChanged(context, enabled);
            }
        }
		/// <Docs>The Context in which the receiver is running.</Docs>
		/// <summary>
		/// When we receive the action media button intent
		/// parse the key event and tell our service what to do.
		/// </summary>
		/// <param name="context">Context.</param>
		/// <param name="intent">Intent.</param>
		public override void OnReceive (Context context, Intent intent)
		{


			if (intent.Action != Intent.ActionMediaButton)
				return;

			//The event will fire twice, up and down.
			// we only want to handle the down event though.
			var key = (KeyEvent) intent.GetParcelableExtra(Intent.ExtraKeyEvent);
			if (key.Action != KeyEventActions.Down)
				return;
	
            var action = MediaPlayerService.ActionPlay;

			switch (key.KeyCode) {
				case Keycode.Headsethook:
				case Keycode.MediaPlayPause:
                action = MediaPlayerService.ActionTogglePlayback;
					break;
				case Keycode.MediaPlay:
                action = MediaPlayerService.ActionPlay;
					break;
				case Keycode.MediaPause:
                action = MediaPlayerService.ActionPause;
					break;
				case Keycode.MediaStop:
                action = MediaPlayerService.ActionStop;
					break;
				case Keycode.MediaNext:
                action = MediaPlayerService.ActionNext;
					break;
				case Keycode.MediaPrevious:
                action = MediaPlayerService.ActionPrevious;
					break;
				default:
					return;
			}

			var remoteIntent = new Intent(action);
			context.StartService(remoteIntent);
		}
        public override void OnReceive(Context context, Intent intent)
        {
            //There's no point in going any further if the service isn't running.
            if (!App.Current.AudioServiceConnection.IsPlayerBound) return;

            //Aaaaand there's no point in continuing if the intent doesn't contain info about headset control inputs.
            var intentAction = intent.Action;
            if (!Intent.ActionMediaButton.Equals(intentAction))
            {
                return;
            }

            var keyEvent = (KeyEvent) intent.GetParcelableExtra(Intent.ExtraKeyEvent);
            if (keyEvent.Action != KeyEventActions.Down) return;

            var keycode = keyEvent.KeyCode;

            //Switch through each event and perform the appropriate action based on the intent that's ben
            if (keycode == Keycode.MediaPlayPause || keycode == Keycode.Headsethook)
            {
                //Toggle play/pause.
                var playPauseIntent = new Intent();
                playPauseIntent.SetAction(AudioPlaybackService.PlayPauseAction);
                context.SendBroadcast(playPauseIntent);
            }

            if (keycode == Keycode.MediaNext)
            {
                //Fire a broadcast that skips to the next track.
                var nextIntent = new Intent();
                nextIntent.SetAction(AudioPlaybackService.NextAction);
                context.SendBroadcast(nextIntent);
            }

            if (keycode == Keycode.MediaPrevious)
            {
                //Fire a broadcast that goes back to the previous track.
                var previousIntent = new Intent();
                previousIntent.SetAction(AudioPlaybackService.PrevAction);
                context.SendBroadcast(previousIntent);
            }
        }
        public override void OnReceive(Context context, Intent intent)
        {
            var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

            Debug.WriteLine("Result of trying to pair with pager: " + device.BondState);

            var message = string.Empty;
            switch (device.BondState)
            {
                case Bond.Bonding:
                    message = "Bonding with device...";
                    break;
                case Bond.Bonded:
                    message = "Successfuly Bonded";
                    break;
                case Bond.None:
                    message = "Failed To Bond";
                    break;
            }
            DialogView.ShowDialog(message, _currentActivity);
        }
Example #23
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            //if (requestCode == 40)
            //{
            //Ringtone ringTone;
            //Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            //Uri uri = data.GetParcelableExtra(RingtoneManager.ExtraRingtonePickedUri);
            //ringTone = RingtoneManager.getRingtone(Xamarin.Forms.Forms.Context, uri);

            Android.Net.Uri ring = (Android.Net.Uri)data.GetParcelableExtra(RingtoneManager.ExtraRingtonePickedUri);
            System.Diagnostics.Debug.WriteLine(ring.ToString());
            //ringTone = RingtoneManager.GetRingtone(Xamarin.Forms.Forms.Context, uri)
            //Toast.makeText(MainActivity.this,
            //		ringTone.getTitle(MainActivity.this),
            //		Toast.LENGTH_LONG).show();
            //ringTone.play();

            //}
            //void ((Activity)Forms.Context).On(){ }
        }
Example #24
0
        //--------------------------------------------------------------
        // METHODS OVERRIDE
        //--------------------------------------------------------------
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;

            // When discovery finds a device
            if(action == BluetoothDevice.ActionFound)
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device =(BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                // If it's already paired, skip it, because it's been listed already
                if(device.BondState != Bond.Bonded)
                {
                    _activity.AddNewDevice(device);
                }
                // When discovery is finished, change the Activity title
            }
            else if(action == BluetoothAdapter.ActionDiscoveryFinished)
            {
                _activity.FinishDiscovery();
            }
        }
        protected override void OnActivityResult(int requestCode, Android.App.Result resultCode, Android.Content.Intent data)
        {
            // retrieve the error code, if available
            int errorCode = -1;

            if (data != null)
            {
                errorCode = data.GetIntExtra(WalletConstants.ExtraErrorCode, -1);
            }
            switch (requestCode)
            {
            case REQUEST_CODE_MASKED_WALLET:
                switch (resultCode)
                {
                case Android.App.Result.Ok:
                    var maskedWallet = data.GetParcelableExtra(WalletConstants.ExtraMaskedWallet).JavaCast <MaskedWallet> ();
                    launchConfirmationPage(maskedWallet);
                    break;

                case Android.App.Result.Canceled:
                    break;

                default:
                    HandleError(errorCode);
                    break;
                }
                break;

            case WalletConstants.ResultError:
                HandleError(errorCode);
                break;

            default:
                base.OnActivityResult(requestCode, resultCode, data);
                break;
            }
        }
        public void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode == AppConfig.REQUEST_CODE_PAYPAL_PAYMENT && data != null) {
                if (resultCode == Result.Ok) {
                    var confirmObj = data.GetParcelableExtra (PaymentActivity.ExtraResultConfirmation);
                    PaymentConfirmation confirm =Android.Runtime.Extensions.JavaCast<PaymentConfirmation> (confirmObj);
                    Console.WriteLine (confirm.ToString ());
                    if (confirm != null) {
                        try
                        {

                        }
                        catch(Exception ex) {
                            Console.WriteLine (confirm.ToString ());
                        }
                    }

                } else if (resultCode == Result.Canceled) {

                } else if ((int)resultCode == PaymentActivity.ResultExtrasInvalid) {

                }
            }
        }
Example #27
0
        /// <summary>
        /// Forwards <c>OnActivityResult</c> to the <c>CardIO</c> plugin. This is a must!
        /// </summary>
        /// <param name="requestCode">Request code</param>
        /// <param name="resultCode">Result code</param>
        /// <param name="data">Intent data</param>
        public static void ForwardActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode == ScanActivityResultCode)
            {
                if (data != null && data.HasExtra(CardIOActivity.ExtraScanResult))
                {
                    CreditCard scanResult = (CreditCard)data.GetParcelableExtra(CardIOActivity.ExtraScanResult);
                    
                    _currentScan._result = new CardIOResult
                    {
                        CreditCardType = scanResult.CardType.ToPclCardType(),
                        CardNumber = scanResult.CardNumber,
                        Cvv = scanResult.Cvv,
                        Expiry = new DateTime(scanResult.ExpiryYear, scanResult.ExpiryMonth, 1),
                        PostalCode = scanResult.PostalCode,
                        Success = true
                    };
                }
                else
                    _currentScan._result = new CardIOResult { Success = false };

                _currentScan._finished = true;
            }
        }
        public override void OnReceive(Context context, Intent intent)
        {
            var bondState = (Bond)intent.GetIntExtra(BluetoothDevice.ExtraBondState, (int)Bond.None);
            var device = new Device((BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice), null, null, 0);
            Console.WriteLine(bondState.ToString());

            if (BondStateChanged == null) return;

            switch (bondState)
            {
                case Bond.None:
                    BondStateChanged(this, new DeviceBondStateChangedEventArgs() { Device = device, State = DeviceBondState.NotBonded });
                    break;

                case Bond.Bonding:
                    BondStateChanged(this, new DeviceBondStateChangedEventArgs() { Device = device, State = DeviceBondState.Bonding });
                    break;

                case Bond.Bonded:
                    BondStateChanged(this, new DeviceBondStateChangedEventArgs() { Device = device, State = DeviceBondState.Bonded });
                    break;

            }
        }
Example #29
0
        protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
        {            
            if (requestCode == LOAD_MASKED_WALLET_REQ_CODE) { // Unique, identifying constant
                if (resultCode == Result.Ok) {

                    var maskedWallet = data.GetParcelableExtra (WalletConstants.ExtraMaskedWallet).JavaCast<MaskedWallet> ();

                    var fullWalletRequest = FullWalletRequest.NewBuilder ()
                        .SetCart (Cart.NewBuilder ()
                            .SetCurrencyCode ("USD")
                            .SetTotalPrice ("20.00")
                            .AddLineItem (LineItem.NewBuilder () // Identify item being purchased
                                .SetCurrencyCode ("USD")
                                .SetQuantity ("1")
                                .SetDescription ("Premium Llama Food")
                                .SetTotalPrice ("20.00")
                                .SetUnitPrice ("20.00")
                                .Build ())
                            .Build ())
                        .SetGoogleTransactionId (maskedWallet.GoogleTransactionId)
                        .Build ();
                    
                    WalletClass.Payments.LoadFullWallet (googleApiClient, fullWalletRequest, LOAD_FULL_WALLET_REQ_CODE);

                } else {
                    base.OnActivityResult (requestCode, resultCode, data);
                }
            } else if (requestCode == LOAD_FULL_WALLET_REQ_CODE) { // Unique, identifying constant
                    
                if (resultCode == Result.Ok) {
                    var fullWallet = data.GetParcelableExtra (WalletConstants.ExtraFullWallet).JavaCast<FullWallet> ();
                    var tokenJson = fullWallet.PaymentMethodToken.Token;

                    var stripeToken = Stripe.Token.FromJson (tokenJson);

                    var msg = string.Empty;

                    if (stripeToken != null) {

                        //TODO: Send token to your server to process a payment with

                        msg = string.Format ("Good news! Stripe turned your credit card into a token: \n{0} \n\nYou can follow the instructions in the README to set up Parse as an example backend, or use this token to manually create charges at dashboard.stripe.com .", 
                            stripeToken.Id);
                        
                    } else {
                        msg = "Failed to create Token";
                    }

                    new AlertDialog.Builder (this)
                        .SetTitle ("Stripe Response")
                        .SetMessage (msg)
                        .SetCancelable (true)
                        .SetNegativeButton ("OK", delegate { })
                        .Show ();                    
                }

            } else {
                base.OnActivityResult (requestCode, resultCode, data);
            }
        }
 public override void OnReceive(Context context, Intent intent)
 {
     if (intent.Action == TileEvent.ActionTileOpened)
     {
         var tileOpenData = (TileEvent)intent.GetParcelableExtra(TileEvent.TileEventData);
         Toast.MakeText(context, string.Format("Tile opened: {0}", tileOpenData.TileName), ToastLength.Short).Show();
     }
     else if (intent.Action == TileEvent.ActionTileButtonPressed)
     {
         var buttonData = (TileButtonEvent)intent.GetParcelableExtra(TileEvent.TileEventData);
         Toast.MakeText(context, string.Format("Button {0} Pressed: {1}", buttonData.ElementId, buttonData.TileName), ToastLength.Short).Show();
     }
     else if (intent.Action == TileEvent.ActionTileClosed)
     {
         var tileCloseData = (TileEvent)intent.GetParcelableExtra(TileEvent.TileEventData);
         Toast.MakeText(context, string.Format("Tile closed: {0}", tileCloseData.TileName), ToastLength.Short).Show();
     }
 }
		/**
	     * Derive {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks#CONTENT_ITEM_TYPE}
	     * {@link Uri} based on incoming {@link Intent}, using
	     * {@link #EXTRA_TRACK} when set.
	     * @param intent
	     * @return Uri
	     */
		private Uri ResolveTrackUri (Intent intent)
		{
			Uri trackUri = (Uri)intent.GetParcelableExtra (EXTRA_TRACK);
			if (trackUri != null) {
				return trackUri;
			} else {
				return ScheduleContract.Sessions.BuildTracksDirUri (mSessionId);
			}
		}
Example #32
0
            public override void OnReceive(Context context, Intent intent)
            {
                string action = intent.Action;

                // When discovery finds a device
                if (action == BluetoothDevice.ActionFound) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra (BluetoothDevice.ExtraDevice);
                // If it's already paired, skip it, because it's been listed already
                if (device.BondState != Bond.Bonded) {
                    newDevicesAA.Add (device.Name + "\n" + device.Address);
                }
                // When discovery is finished, change the Activity title
                } else if (action == BluetoothAdapter.ActionDiscoveryFinished) {
                _chat.SetProgressBarIndeterminateVisibility (false);
                _chat.SetTitle (Resource.String.select_device);
                if (newDevicesAA.Count == 0) {
                    var noDevices = _chat.Resources.GetText (Resource.String.none_found).ToString ();
                    newDevicesAA.Add (noDevices);
                }
                }
            }
Example #33
0
            public override void OnReceive(Context context, Intent intent)
            {
                String action = intent.Action;

                // When discovery finds a device
                if (BluetoothDevice.ACTION_FOUND.Equals(action))
                {
                    // Get the BluetoothDevice object from the Intent
                    BluetoothDevice device = intent.GetParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE);
                    // If it's already paired, skip it, because it's been listed already
                    if (device.GetBondState() != BluetoothDevice.BOND_BONDED)
                    {
                        activity.mNewDevicesArrayAdapter.Add(device.GetName() + "\n" + device.GetAddress());
                    }
                    // When discovery is finished, change the Activity title
                }
                else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.Equals(action))
                {
                    activity.SetProgressBarIndeterminateVisibility(false);
                    activity.SetTitle(R.String.select_device);
                    if (activity.mNewDevicesArrayAdapter.GetCount() == 0)
                    {
                        var noDevices = activity.Resources.GetText(R.String.none_found).ToString();
                        activity.mNewDevicesArrayAdapter.Add(noDevices);
                    }
                }
            }
Example #34
0
		public void OnNewIntent (object sender, Intent e)
		{
		    droidTag = e.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

			nfcTag.TechList = new List<string>(droidTag.GetTechList());
			nfcTag.Id = droidTag.GetId();

			if (GetNdef (droidTag) == null) 
			{
				nfcTag.IsNdefSupported = false;
			}
			else 
			{
				nfcTag.IsNdefSupported = true;
				Ndef ndef = GetNdef (droidTag);
				nfcTag.NdefMessage = ReadNdef (ndef);
				nfcTag.IsWriteable = ndef.IsWritable;
				nfcTag.MaxSize = ndef.MaxSize;
			}

			RaiseNewTag(nfcTag);
		}
Example #35
0
 void HandleLocationUpdate(Intent intent)
 {
     var newLocation = intent.GetParcelableExtra (LocationClient.KeyLocationChanged).JavaCast<Location> ();
     if (lastLocation != null) {
         if (currentBikingState == BikingState.Biking || currentBikingState == BikingState.InGrace)
             currentDistance += lastLocation.DistanceTo (newLocation);
         currentFix = newLocation.Time;
     } else {
         startFix = newLocation.Time;
         lastLocation = prevStoredLocation;
         if (lastLocation != null)
             currentDistance += lastLocation.DistanceTo (newLocation);
         prevStoredLocation = null;
     }
     TripDebugLog.LogPositionEvent (newLocation.Latitude,
                                    newLocation.Longitude,
                                    lastLocation == null ? 0 : lastLocation.DistanceTo (newLocation),
                                    currentDistance);
     lastLocation = newLocation;
 }
Example #36
0
        public void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent data)
        {
            if (requestCode == PayPalManager.REQUEST_CODE_PAYMENT)
            {
                if (resultCode == Result.Ok)
                {
                    PaymentConfirmation confirm =
                        (PaymentConfirmation)data.GetParcelableExtra(PaymentActivity.ExtraResultConfirmation);
                    if (confirm != null)
                    {
                        try {
                            System.Diagnostics.Debug.WriteLine(confirm.ToJSONObject().ToString(4));
                            System.Diagnostics.Debug.WriteLine(confirm.Payment.ToJSONObject().ToString(4));

                            /**
                             *  TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
                             * or consent completion.
                             * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                             * for more details.
                             *
                             * For sample mobile backend interactions, see
                             * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
                             */
                            Toast.MakeText(
                                Context.ApplicationContext,
                                "PaymentConfirmation info received from PayPal", ToastLength.Short)
                            .Show();
                        } catch (JSONException e) {
                            System.Diagnostics.Debug.WriteLine("an extremely unlikely failure occurred: " + e.Message);
                        }
                    }
                }
                else if (resultCode == Result.Canceled)
                {
                    System.Diagnostics.Debug.WriteLine("The user canceled.");
                }
                else if ((int)resultCode == PaymentActivity.ResultExtrasInvalid)
                {
                    System.Diagnostics.Debug.WriteLine(
                        "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
                }
            }
            else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT)
            {
                if (resultCode == Result.Ok)
                {
                    PayPalAuthorization auth = (Xamarin.PayPal.Android.PayPalAuthorization)data.GetParcelableExtra(PayPalFuturePaymentActivity.ExtraResultAuthorization);
                    if (auth != null)
                    {
                        try {
                            System.Diagnostics.Debug.WriteLine(auth.ToJSONObject().ToString(4));

                            String authorization_code = auth.AuthorizationCode;
                            System.Diagnostics.Debug.WriteLine(authorization_code);

                            sendAuthorizationToServer(auth);
                            Toast.MakeText(
                                Context.ApplicationContext,
                                "Future Payment code received from PayPal", ToastLength.Long)
                            .Show();
                        } catch (JSONException e) {
                            System.Diagnostics.Debug.WriteLine("an extremely unlikely failure occurred: " + e.Message);
                        }
                    }
                }
                else if (resultCode == Result.Ok)
                {
                    System.Diagnostics.Debug.WriteLine("The user canceled.");
                }
                else if ((int)resultCode == PayPalFuturePaymentActivity.ResultExtrasInvalid)
                {
                    System.Diagnostics.Debug.WriteLine(
                        "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
                }
            }
            else if (requestCode == REQUEST_CODE_PROFILE_SHARING)
            {
                if (resultCode == Result.Ok)
                {
                    PayPalAuthorization auth = (Xamarin.PayPal.Android.PayPalAuthorization)data.GetParcelableExtra(PayPalProfileSharingActivity.ExtraResultAuthorization);
                    if (auth != null)
                    {
                        try {
                            System.Diagnostics.Debug.WriteLine(auth.ToJSONObject().ToString(4));

                            String authorization_code = auth.AuthorizationCode;
                            System.Diagnostics.Debug.WriteLine(authorization_code);

                            sendAuthorizationToServer(auth);
                            Toast.MakeText(
                                Context.ApplicationContext,
                                "Profile Sharing code received from PayPal", ToastLength.Short)
                            .Show();
                        } catch (JSONException e) {
                            System.Diagnostics.Debug.WriteLine("an extremely unlikely failure occurred: " + e.Message);
                        }
                    }
                }
                else if (resultCode == Result.Canceled)
                {
                    System.Diagnostics.Debug.WriteLine("The user canceled.");
                }
                else if ((int)resultCode == PayPalFuturePaymentActivity.ResultExtrasInvalid)
                {
                    System.Diagnostics.Debug.WriteLine(
                        "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
                }
            }
        }