public override void OnReceive(Context context, Intent intent)
		{
			if (!MainActivity.REPLY_ACTION.Equals(intent.Action))
				return;


			var requestId = intent.GetIntExtra(MainActivity.REQUEST_CODE_KEY, -1);
			if (requestId == -1)
				return;

			var reply = GetMessageText(intent);
			using (var notificationManager = NotificationManagerCompat.From(context))
			{
				// Create new notification to display, or re-build existing conversation to update with new response
				var notificationBuilder = new NotificationCompat.Builder(context);
				notificationBuilder.SetSmallIcon(Resource.Drawable.reply);
				notificationBuilder.SetContentText(Application.Context.GetString(Resource.String.replied));
				var repliedNotification = notificationBuilder.Build();


				// Call notify to stop progress spinner. 
				notificationManager.Notify(requestId, repliedNotification);
			}

			Toast.MakeText(context, $"Message sent: {reply}", ToastLength.Long).Show();
		}
Ejemplo n.º 2
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;
		}
Ejemplo n.º 3
0
        public override void OnReceive(Context context, Intent intent)
        {
            var level = intent.GetIntExtra(BatteryManager.ExtraLevel, -1);
            var scale = intent.GetIntExtra(BatteryManager.ExtraScale, -1);

            var batteryPct = level / (float)scale;

            _batteryLevel.Text = string.Format("{000} %", batteryPct * 100);
            _batteryHealth.Text = ((BatteryHealth)intent.GetIntExtra(BatteryManager.ExtraHealth, 0)).ToString();
            _batteryTemp.Text = string.Format("{0:0.00} C", intent.GetIntExtra(BatteryManager.ExtraTemperature, 0) / 10.0);
            _batteryVoltage.Text = intent.GetIntExtra(BatteryManager.ExtraVoltage, 0) + " mV";
        }
		protected override void OnHandleIntent (Intent intent)
		{
			google_api_client.BlockingConnect (TIME_OUT_MS, TimeUnit.Milliseconds);
			Android.Net.Uri dataItemUri = intent.Data;
			if (!google_api_client.IsConnected) {
				Log.Error (TAG, "Failed to update data item " + dataItemUri +
				" because client is disconnected from Google Play Services");
				return;
			}
			var dataItemResult = WearableClass.DataApi.GetDataItem (
				google_api_client, dataItemUri).Await ().JavaCast<IDataApiDataItemResult> ();

			var putDataMapRequest = PutDataMapRequest.CreateFromDataMapItem (
				DataMapItem.FromDataItem (dataItemResult.DataItem));
			var dataMap = putDataMapRequest.DataMap;

			//update quiz status variables
			int questionIndex = intent.GetIntExtra (EXTRA_QUESTION_INDEX, -1);
			bool chosenAnswerCorrect = intent.GetBooleanExtra (EXTRA_QUESTION_CORRECT, false);
			dataMap.PutInt (Constants.QUESTION_INDEX, questionIndex);
			dataMap.PutBoolean (Constants.CHOSEN_ANSWER_CORRECT, chosenAnswerCorrect);
			dataMap.PutBoolean (Constants.QUESTION_WAS_ANSWERED, true);
			PutDataRequest request = putDataMapRequest.AsPutDataRequest ();
			WearableClass.DataApi.PutDataItem (google_api_client, request).Await ();

			//remove this question notification
			((NotificationManager)GetSystemService (NotificationService)).Cancel (questionIndex);
			google_api_client.Disconnect ();
		}
Ejemplo n.º 5
0
 public override void OnReceive(Context context, Intent intent)
 {
     string action = intent.Action;
     if (WifiP2pManager.WifiP2pStateChangedAction == action)
     {
         // Determine if Wifi Direct mode is enabled
         int state = intent.GetIntExtra(WifiP2pManager.ExtraWifiState, -1);
         Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> WifiDirectReceiver - OnReceive - WifiP2pStateChangedAction - state: {0}", state);
         if (state == (int)WifiP2pState.Enabled)
         {
             // enabled
         }
         else
         {
             // disabled
         }
     }
     else if (WifiP2pManager.WifiP2pPeersChangedAction == action)
     {
         Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> WifiDirectReceiver - OnReceive - WifiP2pPeersChangedAction");
         _manager.RequestPeers(_channel, _peerListListener);
     }
     else if (WifiP2pManager.WifiP2pConnectionChangedAction == action)
     {
         Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> WifiDirectReceiver - OnReceive - WifiP2pConnectionChangedAction");
     }
     else if (WifiP2pManager.WifiP2pThisDeviceChangedAction == action)
     {
         Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> WifiDirectReceiver - OnReceive - WifiP2pThisDeviceChangedAction");
     }
 }
    /// <summary>
    /// Finish the execution from previous <see cref="StartWakefulService(Context, Intent)"/>.
    /// </summary>
    /// <remarks>
    /// Any wake lock that was being held will now be released.
    /// </remarks>
    /// <param name="intent">The <see cref="Intent"/> that was originally generated by <see cref="StartWakefulService(Context, Intent)"/></param>
    /// <returns><c>true</c> if the intent is associated with a wake lock that is now released.
    /// Returns <c>false</c> if there was no wake lock specified for it.</returns>
    internal static bool CompleteWakefulIntent(Intent intent) {
      int id = intent.GetIntExtra(ExtraWakeLockId, 0);
      if (id == 0) {
        return false;
      }

      lock (activeWakeLocksMutex) {
        PowerManager.WakeLock wl = activeWakeLocks[id];
        if (wl != null) {
          wl.Release();
          activeWakeLocks.Remove(id);

          return true;
        }

        // We return true whether or not we actually found the wake lock
        // the return code is defined to indicate whether the Intent contained
        // an identifier for a wake lock that it was supposed to match.
        // We just log a warning here if there is no wake lock found, which could
        // happen for example if this function is called twice on the same
        // intent or the process is killed and restarted before processing the intent.
        Android.Util.Log.Warn("ParseWakefulHelper", "No active wake lock id #" + id);
        return true;
      }
    }
        public override void OnReceive(Context context, Intent intent)
        {
            var action = intent.Action;

            switch (action)
            {
                case WifiP2pManager.WifiP2pStateChangedAction:
                    WifiP2pState state = (WifiP2pState)intent.GetIntExtra(WifiP2pManager.ExtraWifiState, -1);
                    P2PManager.Available = state == WifiP2pState.Enabled;
                    break;
                case WifiP2pManager.WifiP2pPeersChangedAction:
                    manager.RequestPeers(channel, new PeerListListener(peerList =>
                    {
                        P2PManager.peerList = peerList.DeviceList;
                        P2PManager.waitForPeerListSuccess = true;
                        P2PManager.waitForPeerList.Set();
                    }));
                    break;
                case WifiP2pManager.WifiP2pConnectionChangedAction:

                    break;
                case WifiP2pManager.WifiP2pThisDeviceChangedAction:

                    break;
            }
        }
 /// <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);
     }
 }
        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);
        }
Ejemplo n.º 10
0
 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     base.OnActivityResult(requestCode, resultCode, data);
     if (resultCode == Result.Ok)
         if (requestCode==tkey)
         {
             EditText tb1 = FindViewById<EditText>(Resource.Id.text);
             tb1.Text = File.ReadAllText(data.GetStringExtra("1"));
             Log.Verbose("FileListFragment", "файл {0} был открыт.", data.GetStringExtra("1"));
             Toast.MakeText(this, "файл выбран" + data.GetStringExtra("1"), ToastLength.Short).Show();
         }
         else
         {
             ttslist[data.GetIntExtra("4",0)] = new elemTts(data.GetStringExtra("1"), data.GetIntExtra("2",0) / 255f + 0.1f,data.GetIntExtra("3",0) / 170f + 0.5f);
         }
 }
Ejemplo n.º 11
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;
        }
        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 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;
            }
        }
 /**
  * If the confirmation page encounters an error it can't handle, it will send the customer back
  * to this page.  The intent should include the error code as an {@code int} in the field
  * {@link WalletConstants#EXTRA_ERROR_CODE}.
  */
 protected override void OnNewIntent(Android.Content.Intent intent)
 {
     if (intent.HasExtra(WalletConstants.ExtraErrorCode))
     {
         int errorCode = intent.GetIntExtra(WalletConstants.ExtraErrorCode, 0);
         HandleError(errorCode);
     }
 }
		public static int? GetRecipeId(Intent intent) {
			var recipeId = intent.GetIntExtra(RecipeId, -1);
			if(recipeId != -1) {
				return recipeId;
			}

			return null;
		}
Ejemplo n.º 16
0
        public static Album GetAlbum (DrunkAudibleMobileDatabase database, Intent intent)
        {
            var album = database
                    .Albums
                    .FirstOrDefault (a => a.Id == intent.GetIntExtra (ALBUM_ID_INTENT_EXTRA, -1));

            return album ?? Album.Empty;
        }
Ejemplo n.º 17
0
             public override void OnReceive(Context context, Intent intent) {
                    if (intent.Action.Equals(ACTION_STARTED)) {
                        callbackData.Text = ("STARTED");
                    } else if (intent.Action.Equals(ACTION_UPDATE)) {
                        callbackData.Text = ("Got update: " + intent.GetIntExtra("value", 0));
                    } else if (intent.Action.Equals(ACTION_STOPPED)) {
                        callbackData.Text = ("STOPPED");
					}
                }
Ejemplo n.º 18
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok && requestCode == 100)
            {
                var selectedHotDog = ds3DataService.GetDS3ObjectById(data.GetIntExtra("selectedDS3ObjectId", 0));
            }
        }
        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);
                            }
                        }
                    }
                }
            }
        }
		public override void OnReceive (Context context, Intent intent)
		{
			Log.Debug (TAG, "onReceive");
			int conversationId = intent.GetIntExtra (CONVERSATION_ID, -1);
			if (conversationId != -1) {
				Log.Debug (TAG, "Conversation " + conversationId + " was read");
				MessageLogger.LogMessage (context, "Conversation " + conversationId + " was read.");
				NotificationManagerCompat.From (context)
					.Cancel (conversationId);
			}
		}
 public override void OnReceive(Context context, Intent intent)
 {
     if (MessagingService.REPLY_ACTION.Equals (intent.Action)) {
         int conversationId = intent.GetIntExtra (MessagingService.CONVERSATION_ID, -1);
         var reply = GetMessageText (intent);
         if (conversationId != -1) {
             Log.Debug (TAG, "Got reply (" + reply + ") for ConversationId " + conversationId);
             MessageLogger.LogMessage (context, "ConversationId: " + conversationId +
             " received a reply: [" + reply + "]");
         }
     }
 }
Ejemplo n.º 22
0
        public static AudioEpisode GetAudioEpisode (Intent intent, Album album)
        {
            if (album == null || album.Episodes == null)
            {
                return AudioEpisode.Empty;
            }

            var episode = album
                    .Episodes
                    .FirstOrDefault (e => e.Id == intent.GetIntExtra (EPISODE_ID_INTENT_EXTRA, -1));

            return episode ?? AudioEpisode.Empty;
        }
Ejemplo n.º 23
0
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            //Parse location info sent to this service from calling activity to make sure there was no error
            Log.Debug("NavUpdateService", "NavUpdateService started");
            startLat = intent.GetDoubleExtra("startLat", -1);
            startLon = intent.GetDoubleExtra("startLon", -1);
            userID   = intent.GetIntExtra("userID", -1);
            lotID    = intent.GetIntExtra("lotID", -1);
            if (startLat == -1 || startLon == -1 || userID == -1 || lotID == -1)
            {
                Toast.MakeText(this, "Received bad info from initiating activity. Please try again.", ToastLength.Long).Show();
            }
            //Build foreground notification to show while service is running then show it
            var notification = new Notification.Builder(this)
                               .SetContentTitle(Resources.GetString(Resource.String.ApplicationName))
                               .SetContentText(GetString(Resource.String.ForeNotificationText))
                               .SetSmallIcon(Resource.Drawable.AutospotsIcon24x24).SetOngoing(true)
                               .Build();

            StartForeground(noteID, notification);
            return(StartCommandResult.Sticky);
        }
        //This function activates when results are returned from child activities
        //http://developer.android.com/training/basics/intents/result.html
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (requestCode == TSPatient.ID)
            {
                if (resultCode == Result.Ok)
                {
                    TSPatient.CurrentTime = data.GetIntExtra("TimeStamp", 0);
                }

            }

            if (requestCode == TSBooking.ID)
            {
                if (resultCode == Result.Ok)
                {
                    TSBooking.CurrentTime = data.GetIntExtra("TimeStamp", 0);
                }

            }

            if (requestCode == TSPrice.ID)
            {
                if (resultCode == Result.Ok)
                {
                    TSPrice.CurrentTime = data.GetIntExtra("TimeStamp", 0);
                }

            }

            if (requestCode == TSPrescription.ID)
            {
                if (resultCode == Result.Ok)
                {
                    TSPrescription.CurrentTime = data.GetIntExtra("TimeStamp", 0);
                }

            }
        }
Ejemplo n.º 25
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);
                    }
                }
            }
Ejemplo n.º 26
0
        public override void OnReceive(Context context, Intent intent)
        {
            int extraStatus = intent.GetIntExtra(BatteryManager.ExtraStatus, -1);
            _status = ((extraStatus == -1) ? (null) : ((BatteryStatus?) extraStatus) );
            isCharging = (_status == BatteryStatus.Charging || _status == BatteryStatus.Full);

            int extraPlugged = intent.GetIntExtra(BatteryManager.ExtraPlugged, -1);
            _chargePlug = ((extraPlugged == -1) ? (null) : ((BatteryPlugged?) extraPlugged));
            usbCharge = (_chargePlug == BatteryPlugged.Usb);
            acCharge = (_chargePlug == BatteryPlugged.Ac);

            int extraLevel = _batteryStatus.GetIntExtra(BatteryManager.ExtraLevel, 0);
            int extraScale = _batteryStatus.GetIntExtra(BatteryManager.ExtraScale, 100);

            if (extraScale != 0)
            {
                batteryLevel = ((extraLevel * 100) / ((float) extraScale));
            }
            else {
                batteryLevel = (float) extraLevel;
            }
        }
Ejemplo n.º 27
0
        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);
        }
Ejemplo n.º 28
0
    public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
    {
        Android.Util.Log.Debug("BackgroundService", "Started BackgroundService");
        Task.Run(async() => {
            while (true)
            {
                await Task.Delay(10000);
                // 開発用。ずっとサーバにアクセスし続けるので一旦何もしないようにする
                // continue;

                DateTime dt = DateTime.Now;
                // 毎日AM9:00のみ一度実行
                if (dt.Hour != 9 && dt.Minute != 0 && dt.Second != 0)
                {
                    // continue;
                }
                string today = dt.ToString("yyyy-MM-dd");

                var bundle = new Bundle();
                global::Xamarin.Forms.Forms.Init(this, bundle);

                // PCLのクラス実行
                madaarumk2.GetObjects go = new madaarumk2.GetObjects();
                int userId = intent.GetIntExtra("userid", 0);
                if (userId == 0)
                {
                    continue;
                }
                string jsonString = await go.GetExpendablesInfo(userId);
                if (jsonString == "null")
                {
                    continue;
                }
                List <madaarumk2.Expendables> expInfo = go.GetAllItemsObjectFromJson(jsonString);
                Dictionary <string, string> item      = new Dictionary <string, string>();

                for (int n = 0; n < expInfo.Count; n++)
                {
                    if (expInfo[n].limit != today)
                    {
                        continue;
                    }
                    // TODO: aliasを使うようにする(要Expendablesクラスの拡張)
                    madaarumk2.BackgroundNotification.Main(expInfo[n].name);
                }
            }
        });

        return(StartCommandResult.Sticky);
    }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
0
		protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
		{
			//
			// A requestCode of 100 indicates this result is from the AddItem Activity.
			// A resultCode of OK means the user touched the SAVE button and not the CANCEL button.
			// The values for the new item are stored in the Intent Extras.
			//
			if (requestCode == 100 && resultCode == Result.Ok)
			{
				string name  = data.GetStringExtra("ItemName");
				int    count = data.GetIntExtra   ("ItemCount", 0);

				MainActivity.Items.Add(new Item(name, count));
			}
		}
Ejemplo n.º 31
0
 /// <exception cref="T:System.InvalidOperationException"></exception>
 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     if (resultCode == Result.Canceled) return;
     if (requestCode ==100)
         StartActivityForResult(typeof(ChoosePlayerActivity), 101);
     if (requestCode ==101)
     {
         var position = data.GetIntExtra("player_id", -1);
         if (position < 0)
             throw new InvalidOperationException ("You should choose player");
         var player = Rep.Instance.Players [position];
         player.Score -= 5;
         ShowDialogOnButtonClick (TaskDialog.Bear, player);
     }
 }
Ejemplo n.º 32
0
 static object GetValue(Intent intent, string name, Type type)
 {
     switch (Type.GetTypeCode (type)) {
     case TypeCode.String:
         return intent.GetStringExtra (name);
     case TypeCode.Single:
         return intent.GetFloatExtra (name, 0);
     case TypeCode.Double:
         return intent.GetDoubleExtra (name, 0);
     case TypeCode.Int32:
         return intent.GetIntExtra (name, 0);
     default:
         throw new Exception ("Type not supported");
     }
 }
Ejemplo n.º 33
0
 public override Android.App.StartCommandResult OnStartCommand(Android.Content.Intent intent, Android.App.StartCommandFlags flags, int startId)
 {
     if (intent != null)
     {
         string action = intent.Action;
         if (Constants.ActionDismiss.Equals(action))
         {
             // We need to dismiss the wearable notification. We delete the DataItem that created the notification to inform the wearable.
             int notificationId = intent.GetIntExtra(Constants.KeyNotificationId, -1);
             if (notificationId == Constants.BothId)
             {
                 DismissWearableNotification(notificationId);
             }
         }
     }
     return(base.OnStartCommand(intent, flags, startId));
 }
        public override void OnReceive(Context context, Intent intent)
        {
            var action = intent.Action;

            if (action != BluetoothAdapter.ActionStateChanged)
                return;

            var state = intent.GetIntExtra(BluetoothAdapter.ExtraState, -1);

            if (state == -1)
            {
                _stateChangedHandler?.Invoke(BluetoothState.Unknown);
                return;
            }

            var btState = (State) state;
            _stateChangedHandler?.Invoke(btState.ToBluetoothState());
        }
Ejemplo n.º 35
0
		public void ShowPhoto (View view)
		{
			Intent intent = new Intent (this, typeof (DetailActivity));

			switch (view.Id) {
			case (Resource.Id.show_photo_1):
				intent.PutExtra ("lat", 37.6329946);
				intent.PutExtra ("lng", -122.4938344);
				intent.PutExtra ("zooom", 14.0f);
				intent.PutExtra ("title", "Pacifica Pier");
				intent.PutExtra ("description", Resources.GetText (Resource.String.lorem));
				intent.PutExtra ("photo", Resource.Drawable.photo1);
				break;
			case (Resource.Id.show_photo_2):
				intent.PutExtra ("lat", 37.73284);
				intent.PutExtra ("lng", -122.503065);
				intent.PutExtra ("zoom", 15.0f);
				intent.PutExtra ("title", "Pink Flamingo");
				intent.PutExtra ("description", Resources.GetText (Resource.String.lorem));
				intent.PutExtra ("photo", Resource.Drawable.photo2);
				break;
			case (Resource.Id.show_photo_3):
				intent.PutExtra ("lat", 36.861897);
				intent.PutExtra ("lng", -111.374438);
				intent.PutExtra ("zoom", 11.0f);
				intent.PutExtra ("title", "Antelope Canyon");
				intent.PutExtra ("description", Resources.GetText (Resource.String.lorem));
				intent.PutExtra ("photo", Resource.Drawable.photo3);
				break;
			case (Resource.Id.show_photo_4):
				intent.PutExtra ("lat", 36.596125);
				intent.PutExtra ("lng", -118.1604282);
				intent.PutExtra ("zoom", 9.0f);
				intent.PutExtra ("title", "Lone Pine");
				intent.PutExtra ("description", Resources.GetText (Resource.String.lorem));
				intent.PutExtra ("photo", Resource.Drawable.photo4);
				break;
			}

			var hero = ((View)(view.Parent)).FindViewById<ImageView> (Resource.Id.photo);
			SPhotoCache.Put (intent.GetIntExtra ("photo", -1), ((BitmapDrawable)hero.Drawable).Bitmap);
			ActivityOptions options = ActivityOptions.MakeSceneTransitionAnimation (this, hero, "photo_hero");
			StartActivity (intent,options.ToBundle());
		}
		public override void OnReceive (Context context, Intent intent)
		{
			if (MessagingService.REPLY_ACTION.Equals (intent.Action)) {
				int conversationId = intent.GetIntExtra (MessagingService.CONVERSATION_ID, -1);
				var reply = GetMessageText (intent);
				if (conversationId != -1) {
					Log.Debug (TAG, "Got reply (" + reply + ") for ConversationId " + conversationId);
					MessageLogger.LogMessage (context, "ConversationId: " + conversationId +
					" received a reply: [" + reply + "]");

					using (var notificationManager = NotificationManagerCompat.From (context)) {
						var notificationBuilder = new NotificationCompat.Builder (context);
						notificationBuilder.SetSmallIcon (Resource.Drawable.notification_icon);
						notificationBuilder.SetLargeIcon (BitmapFactory.DecodeResource (context.Resources, Resource.Drawable.android_contact));
						notificationBuilder.SetContentText (context.GetString (Resource.String.replied));
						Notification repliedNotification = notificationBuilder.Build ();
						notificationManager.Notify (conversationId, repliedNotification);
					}
				}
			}
		}
        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;
            }
        }
Ejemplo n.º 38
0
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            bool portChanged = false;

            if (intent.HasExtra("UDPPort"))
            {
                int port = intent.GetIntExtra("UDPPort", Settings.Settings.Instance.UdpPort);
                if (port != Settings.Settings.Instance.UdpPort)
                {
                    Settings.Settings.Instance.UdpPort = port;
                    Settings.Settings.Instance.Write(ApplicationContext);
                    portChanged = true;
                }
            }
            if (!mIsInitialized)
            {
                System.Threading.ThreadPool.QueueUserWorkItem((state) => {
                    lock (lockObject)
                    {
                        try
                        {
                            Initialize();
                            UpdateNotification(true);
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                            ShowToast(ex.Message);
                        }
                    }
                });
                mIsInitialized = true;
            }
            else if (portChanged)
            {
                System.Threading.ThreadPool.QueueUserWorkItem((state) => {
                    lock (lockObject)
                    {
                        try
                        {
                            Shutdown();
                            Initialize();
                            UpdateNotification(true);
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                            ShowToast(ex.Message);
                        }
                    }
                });
            }
            else
            {
                System.Threading.ThreadPool.QueueUserWorkItem((state) => {
                    lock (lockObject)
                    {
                        try
                        {
                            if (m_Network.ClientConnected)
                            {
                                m_Network.DisconnectClient(true);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                            ShowToast(ex.Message);
                        }
                    }
                });
            }
            return(StartCommandResult.Sticky);
        }