public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { isRunning = true; Log.Debug(logTag, "Service OnStartCommand - {0}", startId); Toast.MakeText(this, "Service Started", ToastLength.Long).Show(); Task.Run(() => { // for (long index = 1 ;; index++) { // TODO: Demo2 - Step 3a - Stop the service when work is complete // for (long index = 1; index < 15; index++) { // TODO: Demo2 - Step 4a - Stop the service when requested for (long index = 1; isRunning && index < 15; index++) { Thread.Sleep(1000); Log.Debug(logTag, "[{0}] Service running - {1}", startId, index); } Log.Debug(logTag, "Service {0} stopping - {1}", startId, isRunning ? "Work complete" : "OnDestroy"); if (isRunning) { // TODO: Demo2 - Step 3b - Tell Android we are done. StopSelf(); } }); // Continue running until stopped. return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { Log.Debug ("BlaChat", "BackgroundService started"); ResetUpdateInterval (); DoWork (); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Console.WriteLine("WidgetService - OnStartCommand - startId: {0} intent.action: {1}", startId, intent.Action); _widgetIds = intent.GetIntArrayExtra(AppWidgetManager.ExtraAppwidgetIds); if (intent.Action == SessionsWidgetActions.SessionsWidgetPrevious.ToString()) { _messengerHub.PublishAsync<PlayerCommandMessage>(new PlayerCommandMessage(this, PlayerCommandMessageType.Previous)); } else if (intent.Action == SessionsWidgetActions.SessionsWidgetPlayPause.ToString()) { _messengerHub.PublishAsync<PlayerCommandMessage>(new PlayerCommandMessage(this, PlayerCommandMessageType.PlayPause)); } else if (intent.Action == SessionsWidgetActions.SessionsWidgetNext.ToString()) { _messengerHub.PublishAsync<PlayerCommandMessage>(new PlayerCommandMessage(this, PlayerCommandMessageType.Next)); } else if (intent.Action == "android.appwidget.action.APPWIDGET_UPDATE") { Console.WriteLine("WidgetService - Updating notification because of APPWIDGET_UPDATE..."); UpdateWidgetView(); } return StartCommandResult.NotSticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Log.Debug(logTag, "OnStartCommand: service is running"); StartLocationUpdates(); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { if (intent.Action.Equals(Constants.ACTION_START_SERVICE)) { if (isStarted) { Log.Info(TAG, "OnStartCommand: The service is already running."); } else { Log.Info(TAG, "OnStartCommand: The service is starting."); RegisterForegroundService(); handler.PostDelayed(runnable, Constants.DELAY_BETWEEN_LOG_MESSAGES); isStarted = true; } } else if (intent.Action.Equals(Constants.ACTION_STOP_SERVICE)) { Log.Info(TAG, "OnStartCommand: The service is stopping."); timestamper = null; StopForeground(true); StopSelf(); isStarted = false; } else if (intent.Action.Equals(Constants.ACTION_RESTART_TIMER)) { Log.Info(TAG, "OnStartCommand: Restarting the timer."); timestamper.Restart(); } // This tells Android not to restart the service if it is killed to reclaim resources. return StartCommandResult.Sticky; }
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; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { _recordAudioActivity = new RecordAudioActivity(); //start recording some timed audio? t = new System.Timers.Timer(); t.Interval = 10000; t.Elapsed += new System.Timers.ElapsedEventHandler(TimerComplete); //start recording the audio StartRecording(); //start the timer t.Start(); //set app title App.SetTitle("Recording Audio"); var nMgr = (NotificationManager)GetSystemService(NotificationService); var notification = new Notification(Resource.Drawable.icon, "Message from AutoResolve service - Recording Audio"); var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(AudioBackgroundService)), 0); notification.SetLatestEventInfo(this, "AutoResolve Service Notification", "Message from demo service", pendingIntent); nMgr.Notify(0, notification); return StartCommandResult.NotSticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { _cts = new CancellationTokenSource(); Task.Run(() => { try { var pendingTaskList = new TaskEnumeratePending(); pendingTaskList.RunEnumeration(_cts.Token).Wait(); } catch (Android.OS.OperationCanceledException) { } finally { if (_cts.IsCancellationRequested) { var message = new CancelledMessage(); Device.BeginInvokeOnMainThread( () => MessagingCenter.Send(message, "CancelledMessage") ); } } }, _cts.Token); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { Log.Debug (TAG, "ActionBootCompleted received"); RestoreGeofences (); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { if (_card == null) { _card = new LiveCard(this, "theCard"); _view = new BasicView(this); _renderer = new LiveCardRenderer(this); _card.SetDirectRenderingEnabled(true).SurfaceHolder.AddCallback(_renderer); var mi = new Intent(this, typeof (MenuActivity)); mi.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask); _card.SetAction(PendingIntent.GetActivity(this, 0, mi, 0)); _card.Attach(this); _card.Publish(LiveCard.PublishMode.Reveal); _renderer.start(); } else { _card.Navigate(); } return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { var LocationServiceIntent = new Intent ("com.ETCTimeApp.SaveLocationService"); pendingSaveLocationServiceIntent = PendingIntent.GetService (this, 0, LocationServiceIntent, 0); alarm = (AlarmManager)this.BaseContext.GetSystemService (Context.AlarmService); //repeat every 10 minutes alarm.SetRepeating (AlarmType.RtcWakeup, 10000, 1 * 5000 * 60, pendingSaveLocationServiceIntent); var pendingIntent = PendingIntent.GetActivity (this, 1, new Intent (this, typeof(MainActivity)), 0); var resultString = "Location service is running on background!"; int ic_small = Resource.Drawable.gps_small; var builder = new NotificationCompat.Builder (this) .SetAutoCancel (true) .SetContentIntent (pendingIntent) .SetContentTitle ("ETC Location Notification") .SetSmallIcon (ic_small) .SetContentText (resultString); // start our service foregrounded, that way it won't get cleaned up from memory pressure StartForeground ((int)NotificationFlags.ForegroundService, builder.Build ()); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { //start v2 //apicall.addReport("Application opened"); t2.Interval = 120000; // = 2 mins t2.Elapsed += new System.Timers.ElapsedEventHandler(t2_Elapsed); t2.Start(); t3.Interval = 30000; // = 4 mins t3.Elapsed += new System.Timers.ElapsedEventHandler(t3_Elapsed); t3.Start(); //stop v2 // get DEVID string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "settingsk.db3"); var db = new SQLiteConnection(dbPath); db.CreateTable<Settings>(); List<Settings> myId = db.Query<Settings>("select devID from Settings where identificator = '1607'"); string gotID = ""; foreach (Settings s in myId) { gotID = s.devID.ToString(); } //devID = myId.Last().devID.ToString(); devID = gotID; //stop getdevid return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { _cts = new CancellationTokenSource (); Task.Run (() => { try { //INVOKE THE SHARED CODE var counter = new TaskCounter(); counter.RunCounter(_cts.Token).Wait(); } catch (OperationCanceledException) { } finally { if (_cts.IsCancellationRequested) { var message = new CancelledMessage(); Device.BeginInvokeOnMainThread ( () => MessagingCenter.Send(message, "CancelledMessage") ); } } }, _cts.Token); return StartCommandResult.Sticky; }
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 override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId) { if (intent.Action.Equals (Constants.ActionStartCooking)) { CreateNotification (intent); return StartCommandResult.Sticky; } return StartCommandResult.NotSticky; }
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { Log.Info ("LocalService", "Received start id " + startId + ": " + intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow); _timer = new Timer(o => { Log.Debug(TAG, "Hello from SimpleService. {0}", DateTime.UtcNow); }, null, 0, TimerWait); return StartCommandResult.NotSticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { if (!_isRunning) { _isRunning = true; _task.Start(); } return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Log.Info("TestService.OnStartCommand", "started"); var startCommandResult = base.OnStartCommand(intent, flags, startId); RegisterReceiver(_sbr, new IntentFilter(AppConstants.SERVICE_COMMAND)); return startCommandResult; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { if (!Settings.IsFireTV ()) { Console.WriteLine ("Not starting KFTV Watcher Service, not FireTV..."); return StartCommandResult.NotSticky; } if (timer == null) { activityManager = ActivityManager.FromContext (this); timer = new Timer (state => { if (Settings.Instance.DisableHomeDetection) { Console.WriteLine ("Disabled Home Detection... Not starting KFTV Watcher Service..."); return; } // Gets the topmost running task var topTask = activityManager.GetRunningTasks (1).FirstOrDefault (); if (topTask == null || topTask.TopActivity == null) return; // We can detect that the firetv home launcher was called // by simply getting the top task's top activity and matching the // package name and class name // Package Name: com.amazon.tv.launcher // Class Name: com.amazon.tv.launcher.ui.HomeActivity if (topTask.TopActivity.PackageName == Settings.HOME_PACKAGE_NAME && topTask.TopActivity.ClassName == Settings.HOME_CLASS_NAME) { var actedAgo = DateTime.UtcNow - acted; // Just to be safe, we don't want to call this multiple times in a row // Also there's a static flag that the firedtv app can set // to allow the user to launch the firetv homescreen if (actedAgo > TimeSpan.FromMilliseconds (500) && !AllowFireTVHome) { //Come back to papa var actIntent = new Intent(ApplicationContext, typeof(MainActivity)); actIntent.AddFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop); StartActivity (actIntent); // Set the flag acted = DateTime.UtcNow; } } else { // It wasn't a match (another task is top) so reset the flag acted = DateTime.MinValue; } }, null, Settings.Instance.HomeDetectIntervalMs, Settings.Instance.HomeDetectIntervalMs); } return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId) { Log.Debug ("DemoService", "DemoService started"); StartServiceInForeground (); DoWork (); return StartCommandResult.NotSticky; }
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; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { base.OnStartCommand (intent, flags, startId); var callDetactor = new PhoneCallDetector (this); var tm = (TelephonyManager)base.GetSystemService (TelephonyService); tm.Listen (callDetactor, PhoneStateListenerFlags.CallState); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { if (!isStarted) { CreateNotifications ("starting"); isStarted = true; } else { CreateNotifications("resuming"); } return StartCommandResult.RedeliverIntent; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { switch (intent.Action) { case ActionPlay: Play(); break; case ActionStop: Stop(); break; case ActionPause: Pause(); break; } //Set sticky as we are a long running operation return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { // Notification notification = new Notification(Resource.Drawable.Icon, "Wings Call Recorder", DateTime.Now.Ticks); // // Intent notificationIntent = new Intent(this, Java.Lang.Class.FromType (typeof(MainActivity))); // PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0); // // notification.SetLatestEventInfo (this, "Wings Call Recorder", "Service is running", pendingIntent); // // StartForeground (333, notification); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { bool playing = intent.GetBooleanExtra("playing", false); if (playing) { mp.Start(); } else { mp.Pause(); } return base.OnStartCommand(intent, flags, startId); }
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { if (intent == null || intent.Action == null) return StartCommandResult.Sticky; var action = intent.Action; if (action.Equals (ACTION_RESPONSE)) { var remoteInputResults = RemoteInput.GetResultsFromIntent (intent); var replyMessage = ""; if (remoteInputResults != null) replyMessage = remoteInputResults.GetCharSequence (EXTRA_REPLY); ProcessIncoming (replyMessage.ToString ()); } else if (action.Equals (MainActivity.ACTION_GET_CONVERSATION)) BroadcastMessage (mCompleteConversation.ToString ()); return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { // Instantiate the builder and set notification elements: notificationBuilder = new Notification.Builder (this) .SetContentTitle ("Test Notification") .SetContentText ("This worked") .SetSmallIcon (Resource.Drawable.vbclogo); // Get the notification manager: notificationManager = GetSystemService (Context.NotificationService) as NotificationManager; ParsePush.ParsePushNotificationReceived += ParsePush_ParsePushNotificationReceived; return StartCommandResult.Sticky; }
/// <summary> /// This will be called once for every intent. /// </summary> /// <param name="intent">Intent.</param> /// <param name="flags">Flags.</param> /// <param name="startId">Start identifier.</param> public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { // Can use intent to pass data to the service. var val = intent.GetStringExtra(IntentValueKey); Toast.MakeText(this, $"OnStartCommand({val})", ToastLength.Long).Show(); var notification = new Notification(Resource.Drawable.Icon, "Service running in the foreground!"); var notificationIntent = new Intent(this, typeof(MainActivity)); var pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0); notification.SetLatestEventInfo(this, "Foreground Service", "Tap to to to App", pendingIntent); StartForeground((int)NotificationFlags.ForegroundService, notification); // Regular Service (unlike IntentService) runs on the main thread so we must take care of threading here. Task.Run(() => { for(int i = 1; i < 999 && !this.cts.IsCancellationRequested; i++) { MainActivity.L($"Processing foreground service...{i}"); Thread.Sleep(1000); } // Stop when done. There is an override that takes an integer parameter. That's the start ID. The service will then only stop // if the current start ID matches the one passed to StopSelf(). This prevents stopping the service internally if there are still Intents pending with // a higher start ID. (Again: stopping stops the ENTIRE service, not just this current workload!) if(!this.cts.IsCancellationRequested) { this.StopSelf(); } }); // Sticky: // This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback. // http://developer.android.com/reference/android/app/Service.html#START_STICKY // Redeliver Intent: // The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it // (and any such pending events will be delivered at the point of restart). // http://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENT // Not sticky: // This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. // An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. // When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off. // http://developer.android.com/reference/android/app/Service.html#START_NOT_STICKY return StartCommandResult.Sticky; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { //TRICK to keep app runing return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { _isServiceRunning = true; _isConnectionBlocked = false; _lastConnect = DateTimeOffset.MinValue; try { _settingsService = MainActivity.Container.Resolve <ISettingsService>(); _eventService = MainActivity.Container.Resolve <IEventService>(); } catch (Exception) { return(StartCommandResult.RedeliverIntent); } _eventService.BlockConnectionEvent += (s, e) => _isConnectionBlocked = (e as BlockConnectionEventArgs).Blocked; _udpClient = new UdpClient(4536); Task.Run(async() => { try { while (_isServiceRunning) { var udpReceiveResult = await _udpClient.ReceiveAsync(); if (!udpReceiveResult.RemoteEndPoint.Address.ToString().Equals(Networker.GetLocalIp())) { var defconStatus = Encoding.ASCII.GetString(udpReceiveResult.Buffer); if (int.TryParse(defconStatus, out int parsedDefconStatus) && !_isConnectionBlocked) { if (parsedDefconStatus > 0 && parsedDefconStatus < 6) { new SettingsService().SaveSetting("DefconStatus", defconStatus.ToString()); Intent widgetIntent = new Intent(this, typeof(MyDefconWidget)); widgetIntent.SetAction("com.marcusrunge.MyDEFCON.DEFCON_UPDATE"); widgetIntent.PutExtra("DefconStatus", defconStatus.ToString()); Intent statusReceiverIntent = new Intent(this, typeof(DefconStatusReceiver)); statusReceiverIntent.SetAction("com.marcusrunge.MyDEFCON.STATUS_RECEIVER_ACTION"); statusReceiverIntent.PutExtra("DefconStatus", defconStatus.ToString()); SendBroadcast(widgetIntent); SendBroadcast(statusReceiverIntent); if (!_settingsService.GetSetting <bool>("IsForegroundServiceEnabled") && _settingsService.GetSetting <bool>("isStatusUpdateAlertEnabled")) { Notifier.AlertWithVibration(); Notifier.AlertWithAudioNotification(this, _settingsService.GetSetting <int>("StatusUpdateAlertSelection")); } } else if (parsedDefconStatus == 0 && _settingsService.GetSetting <bool>("IsMulticastEnabled") && DateTimeOffset.Now > _lastConnect.AddSeconds(5)) { Intent tcpActionIntent = new Intent(this, typeof(TcpActionReceiver)); tcpActionIntent.SetAction("com.marcusrunge.MyDEFCON.TCP_ACTION"); tcpActionIntent.PutExtra("RemoteEndPointAddress", udpReceiveResult.RemoteEndPoint.Address.ToString()); SendBroadcast(tcpActionIntent); _lastConnect = DateTimeOffset.Now; } } _isConnectionBlocked = false; } } } catch { } }, _cancellationToken); //return base.OnStartCommand(intent, flags, startId); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { new Task(() => { System.Timers.Timer timer = new System.Timers.Timer(); //ApprovalRepository repo = new ApprovalRepository(); timer.Interval = 10000; timer.Elapsed += (s, e) => { Intent notiIntent = null; BitopiApplication bitopiApplication = (BitopiApplication)this.ApplicationContext; try { if (bitopiApplication.User == null || String.IsNullOrEmpty(bitopiApplication.User.UserCode) == true) { ISharedPreferences pref = Application.Context.GetSharedPreferences("_bitopi_UserInfo", FileCreationMode.Private); string _userCode = pref.GetString("UserCode", String.Empty); ISharedPreferences prefToken = Application.Context.GetSharedPreferences("_bitopi_DeviceToken", FileCreationMode.Private); string Token = prefToken.GetString("Token", String.Empty); if (String.IsNullOrEmpty(Token)) { bitopiApplication.MacAddress = Guid.NewGuid().ToString(); prefToken.Edit().PutString("Token", bitopiApplication.MacAddress).Commit(); } else { bitopiApplication.MacAddress = Token; } if (_userCode == "") { notiIntent = new Intent(this, typeof(LoginActivity)); } else { notiIntent = new Intent(this, typeof(BitopiActivity)); bitopiApplication.User = new UserModel() { UserCode = _userCode }; string url = RepositorySettings.BaseURl + "Notification?UserID=" + Cipher.Encrypt(bitopiApplication.User.UserCode) + "&DeviceID=" + bitopiApplication.MacAddress; HttpClient client = new HttpClient(); HttpResponseMessage result = client.GetAsync(url).Result; var messages = JsonConvert.DeserializeObject <List <BitopiGcmMessage> >(result.Content.ReadAsStringAsync().Result); if (messages != null && messages.Count > 0) { SendNotification(messages.First(), bitopiApplication.MacAddress); } } } else { notiIntent = new Intent(this, typeof(BitopiActivity)); } int UpdateVersion = new AccountRepository().GetVersion(); int lastUpdateVersion = DBAccess.Database.LastVersion(); if (lastUpdateVersion == 0) { lastUpdateVersion = this.PackageManager.GetPackageInfo(this.PackageName, Android.Content.PM.PackageInfoFlags.MetaData).VersionCode; DBAccess.Database.InsertVersion(lastUpdateVersion); } if (UpdateVersion > lastUpdateVersion) { int requestID = DateTime.Now.Millisecond; DBAccess.Database.DeleteVersion(lastUpdateVersion); DBAccess.Database.InsertVersion(UpdateVersion); notiIntent = new Intent(this, typeof(DownloadNewVersionActivity)); notiIntent.AddFlags(ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(ApplicationContext, requestID, notiIntent, 0);//requestID = DateTime.Now.Millisecond; var notificationBuilder = new NotificationCompat.Builder(this) .SetSmallIcon(BitopiApprovalSystem.Resource.Drawable.bitopiLogo) .SetContentTitle("Bitopi Approval System") .SetContentText("New Version Arrived") .SetAutoCancel(true) .SetContentIntent(pendingIntent) .SetDefaults(NotificationCompat.DefaultSound); var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService); //new UserRepository().GetNotificationCacheAsCompleted(gcmMsg.NotificationExecId); notificationManager.Notify(requestID, notificationBuilder.Build()); } } catch (Exception ex) { //CustomLogger.CustomLog("From Activity: " + Line + "\nMessage: " + ex.Message + "\nStack Trace: " + ex.StackTrace + "\n\n", "", bitopiApplication.User != null ? // bitopiApplication.User.UserName : ""); } }; timer.Enabled = true; }).Start(); return(base.OnStartCommand(intent, flags, startId)); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Task.Run(() => CheckRecurringPayments()); return(base.OnStartCommand(intent, flags, startId)); }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { // start your service logic here Log.Debug(TAG, "StartCommandResult"); Uri requestUri = intent.Data; if (requestUri == null) { StopSelf(); Log.Debug(TAG, "Request URI was NULL"); } else { Log.Debug(TAG, $"OnStartCommand requestUri {requestUri}, flags={flags}, startid={startId}"); DisplayNotification(); DisplayToastToUser(); // <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService); NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo; if (networkInfo.IsConnected) { var jsonResponse = GetRemoteJSONStringData(requestUri); } StopSelf(); //Stop (and destroy) the service } // Return the correct StartCommandResult for the type of service you are building return(StartCommandResult.NotSticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Task.Run(() => SyncBackups()); return(base.OnStartCommand(intent, flags, startId)); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { timer.scheduleAtFixedRate(new mainTask(), 0, 5000); return(StartCommandResult.NotSticky); }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { System.Diagnostics.Debug.WriteLine("Geofence Service - Started"); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { record = new AudioRecord(Android.Media.AudioSource.Mic, AUDIO_SAMPLE_RATE, Android.Media.ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, CAPTURE_CACHE_SIZE); ws = new WebSocket(WEB_SOCKET_URL); /// 文字列受信 ws.MessageReceived += (s, e) => { Console.WriteLine("{0}:String Received:{1}", DateTime.Now.ToString(), e.Message); }; /// バイナリ受信 ws.DataReceived += (s, e) => { Console.WriteLine("{0}:Binary Received Length:{1}", DateTime.Now.ToString(), e.Data.Length); }; /// サーバ接続完了 ws.Opened += (s, e) => { Console.WriteLine("{0}:Server connected.", DateTime.Now.ToString()); }; /// サーバ接続開始 /// TaskFactory taskFactory = new TaskFactory(); tokenSource = new CancellationTokenSource(); byte[] audioBuffer = new byte[CAPTURE_CACHE_SIZE / 4]; AudioTrack audioTrack = new AudioTrack(Android.Media.Stream.Music, 44100, Android.Media.ChannelOut.Mono, Android.Media.Encoding.Pcm16bit, CAPTURE_CACHE_SIZE, Android.Media.AudioTrackMode.Stream); task = taskFactory.StartNew(() => { Console.WriteLine("NEW CONNECTION!!"); ws.Open(); record.StartRecording(); audioTrack.Play(); /// 送受信ループ while (true) { // var str = "aaaaa"; tokenSource.Token.ThrowIfCancellationRequested(); if (ws.State == WebSocketState.Open) { record.Read(audioBuffer, 0, audioBuffer.Length, 0); audioTrack.Write(audioBuffer, 0, audioBuffer.Length); ws.Send(audioBuffer, 0, audioBuffer.Length); } else { Console.WriteLine("{0}:wait...", DateTime.Now.ToString()); } } }); Task playTask = new Task(() => { while (true) { } }); playTask.Start(); ws.Close(); /* * TaskFactory taskFactory = new TaskFactory(); * tokenSource = new CancellationTokenSource(); * * task = taskFactory.StartNew(() => * { * for (int i = 0; i < 30; i++) * { * tokenSource.Token.ThrowIfCancellationRequested(); * var str = i + "aaaaa"; * Console.WriteLine(str); * Thread.Sleep(500); * } * }, tokenSource.Token); */ return(base.OnStartCommand(intent, flags, startId)); }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { try { if (MFloatingViewManager == null) { RunService = true; DisplayMetrics metrics = new DisplayMetrics(); //DisplayMetrics metrics = Resources.DisplayMetrics; var windowManager = GetSystemService(WindowService).JavaCast <IWindowManager>(); windowManager?.DefaultDisplay?.GetRealMetrics(metrics); if (Inflater == null) { Inflater = LayoutInflater.From(Application.Context); } var iconView = Inflater?.Inflate(Resource.Layout.WidgetChatHeadLayout, null, false); Image = iconView?.FindViewById <ImageView>(Resource.Id.imageFloating); Image?.SetOnClickListener(this); try { DataUser = JsonConvert.DeserializeObject <FloatingObject>(intent.GetStringExtra("UserData")); if (DataUser != null) { Glide.With(Application.Context).Load(DataUser.Avatar).Apply(new RequestOptions().CircleCrop().Placeholder(Resource.Drawable.no_profile_image_circle)).Into(Image); if (!string.IsNullOrEmpty(DataUser.MessageCount) || DataUser.MessageCount != "0") { ShowOrHideBadgeView(Convert.ToInt32(DataUser.MessageCount), true); } } } catch (Exception e) { Methods.DisplayReportResultTrack(e); } MFloatingViewManager = new FloatingViewManager(Application.Context, this); MFloatingViewManager.SetFixedTrashIconImage(Application.Context.GetDrawable(Resource.Drawable.ic_trash_fixed)); MFloatingViewManager.SetActionTrashIconImage(Application.Context.GetDrawable(Resource.Drawable.ic_trash_action)); MFloatingViewManager.SetSafeInsetRect((Rect)intent.GetParcelableExtra(ExtraCutoutSafeArea)); // Setting Options(you can change options at any time) FloatingViewManager.Options options = LoadDynamicOptions(metrics); switch (AppSettings.DisplayModeSettings) { case "Always": MFloatingViewManager.SetDisplayMode(FloatingViewManager.DisplayModeShowAlways); break; case "FullScreen": MFloatingViewManager.SetDisplayMode(FloatingViewManager.DisplayModeHideFullscreen); break; case "Hide": MFloatingViewManager.SetDisplayMode(FloatingViewManager.DisplayModeHideAlways); break; } MFloatingViewManager.AddViewToWindow(iconView, options); return(StartCommandResult.Sticky); } else { if (Image != null) { if (!string.IsNullOrEmpty(DataUser.MessageCount) || DataUser.MessageCount != "0") { var x = Convert.ToInt32(DataUser.MessageCount); if (x >= 1 && AppSettings.LastChatSystem == SystemApiGetLastChat.Old) { x++; } ShowOrHideBadgeView(x, true); } } } return(StartCommandResult.NotSticky); } catch (Exception e) { Methods.DisplayReportResultTrack(e); return(StartCommandResult.NotSticky); } }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { RegisterForegroundService(); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) // HIER DRIN MUSS GECALLED WERDEN! { DispatchNotificationThatServiceIsRunning(); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Kp2aLog.Log("Received intent to provide access to entry"); if (_stopOnLockBroadcastReceiver == null) { _stopOnLockBroadcastReceiver = new StopOnLockBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_stopOnLockBroadcastReceiver, filter); } if ((intent.Action == Intents.ShowNotification) || (intent.Action == Intents.UpdateKeyboard)) { String entryId = intent.GetStringExtra(EntryActivity.KeyEntry); String searchUrl = intent.GetStringExtra(SearchUrlTask.UrlToSearchKey); if (entryId == null) { Kp2aLog.Log("received intent " + intent.Action + " without KeyEntry!"); #if DEBUG throw new Exception("invalid intent received!"); #endif return(StartCommandResult.NotSticky); } PwEntryOutput entry; try { ElementAndDatabaseId fullId = new ElementAndDatabaseId(entryId); if (((App.Kp2a.LastOpenedEntry != null) && (fullId.ElementId.Equals(App.Kp2a.LastOpenedEntry.Uuid)))) { entry = App.Kp2a.LastOpenedEntry; } else { Database entryDb = App.Kp2a.GetDatabase(fullId.DatabaseId); entry = new PwEntryOutput(entryDb.EntriesById[fullId.ElementId], entryDb); } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); //seems like restarting the service happened after closing the DB StopSelf(); return(StartCommandResult.NotSticky); } if (intent.Action == Intents.ShowNotification) { //first time opening the entry -> bring up the notifications bool activateKeyboard = intent.GetBooleanExtra(EntryActivity.KeyActivateKeyboard, false); DisplayAccessNotifications(entry, activateKeyboard, searchUrl); } else //UpdateKeyboard { #if !EXCLUDE_KEYBOARD //this action is received when the data in the entry has changed (e.g. by plugins) //update the keyboard data. //Check if keyboard is (still) available if (Keepass2android.Kbbridge.KeyboardData.EntryId == entry.Uuid.ToHexString()) { MakeAccessibleForKeyboard(entry, searchUrl); } #endif } } if (intent.Action == Intents.CopyStringToClipboard) { TimeoutCopyToClipboard(intent.GetStringExtra(_stringtocopy)); } if (intent.Action == Intents.ActivateKeyboard) { ActivateKp2aKeyboard(); } if (intent.Action == Intents.ClearNotificationsAndData) { ClearNotifications(); } return(StartCommandResult.RedeliverIntent); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { return(base.OnStartCommand(intent, flags, startId)); }
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); }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { MemoTech.Scripts.Utility.ConnectLog.ConnectionCount = 0; var t = new Thread(() => { while (true) { Thread.Sleep(60000); BluetoothLEManager.Instance.BeginScanningForDevices(); Thread.Sleep(5000); BluetoothLEManager.Instance.StopScanningForDevices(); MemoTech.Scripts.Utility.ConnectLog.ConnectionCount += 1; Console.WriteLine("Scan!"); if (BluetoothLEManager.Instance.Check == MemoTech.Scripts.Utility.State.Share) { BluetoothLEManager.Instance.Check = MemoTech.Scripts.Utility.State.Start; StopSelf(); } } }); t.Start(); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { HandleIntent(intent); return base.OnStartCommand(intent, flags, startId); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { MessagingCenter.Send <object, string>(this, "UpdateLabel", "Hello from Android"); return(StartCommandResult.NotSticky); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { //return base.OnStartCommand(intent, flags, startId); m_pAlarm.SetAlarm(this); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper; // there might be a race condition between the calling of this method and the stopping/disposal of the service helper. // if the service helper is stopped/disposed before the service is stopped but after this method is called (e.g., by // an alarm callback), the service helper will be null. if (serviceHelper != null) { serviceHelper.Logger.Log("Sensus service received start command (startId=" + startId + ", flags=" + flags + ").", LoggingLevel.Normal, GetType()); // promote this service to a foreground, for several reasons: it's honest and transparent. it lets us work effectively with the // android 8.0 restrictions on background services (we can run forever without being killed, we receive background location // updates). it's okay to call this multiple times. doing so will simply update the notification. if (_foregroundServiceNotificationBuilder == null) { PendingIntent mainActivityPendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(AndroidMainActivity)), 0); _foregroundServiceNotificationBuilder = (SensusContext.Current.Notifier as AndroidNotifier).CreateNotificationBuilder(this, AndroidNotifier.SensusNotificationChannel.ForegroundService) .SetSmallIcon(Resource.Drawable.ic_launcher) .SetContentIntent(mainActivityPendingIntent) .SetOngoing(true); UpdateForegroundServiceNotificationBuilder(); StartForeground(FOREGROUND_SERVICE_NOTIFICATION_ID, _foregroundServiceNotificationBuilder.Build()); } else { ReissueForegroundServiceNotification(); } // acquire wake lock before this method returns to ensure that the device does not sleep prematurely, interrupting the execution of a callback. serviceHelper.KeepDeviceAwake(); Task.Run(async() => { // 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. await serviceHelper.StartAsync(); if (intent == null) { serviceHelper.LetDeviceSleep(); } else { DisplayPage displayPage; // is this a callback intent? if (intent.GetBooleanExtra(CallbackScheduler.SENSUS_CALLBACK_KEY, false)) { // service the callback -- the matching LetDeviceSleep will be called therein await(SensusContext.Current.CallbackScheduler as AndroidCallbackScheduler).ServiceCallbackAsync(intent); } // should we display a page? else if (Enum.TryParse(intent.GetStringExtra(Notifier.DISPLAY_PAGE_KEY), out displayPage)) { serviceHelper.BringToForeground(); SensusContext.Current.Notifier.OpenDisplayPage(displayPage); serviceHelper.LetDeviceSleep(); } else { serviceHelper.LetDeviceSleep(); } } }); } // if the service is killed by the system (e.g., due to resource constraints), ask the system to restart // the service when possible. return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper; // there might be a race condition between the calling of this method and the stopping/disposal of the service helper. // if the service helper is stopped/disposed before the service is stopped but after this method is called, the service // helper will be null. if (serviceHelper != null) { serviceHelper.Logger.Log("Sensus service received start command (startId=" + startId + ", flags=" + flags + ").", LoggingLevel.Normal, GetType()); // acquire wake lock before this method returns to ensure that the device does not sleep prematurely, interrupting the execution of a callback. serviceHelper.KeepDeviceAwake(); // 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 != null) { // is this a callback intent? if (intent.GetBooleanExtra(SensusServiceHelper.SENSUS_CALLBACK_KEY, false)) { string callbackId = intent.GetStringExtra(SensusServiceHelper.SENSUS_CALLBACK_ID_KEY); // if the user removes the main activity from the switcher, the service's process will be killed and restarted without notice, and // we'll have no opportunity to unschedule repeating callbacks. when the service is restarted we'll reinitialize the service // helper, restart the repeating callbacks, and we'll then have duplicate repeating callbacks. handle the invalid callbacks below. // if the callback is scheduled, it's fine. if it's not, then unschedule it. if (serviceHelper.CallbackIsScheduled(callbackId)) { bool repeating = intent.GetBooleanExtra(SensusServiceHelper.SENSUS_CALLBACK_REPEATING_KEY, false); int repeatDelayMS = intent.GetIntExtra(SensusServiceHelper.SENSUS_CALLBACK_REPEAT_DELAY_KEY, -1); bool repeatLag = intent.GetBooleanExtra(SensusServiceHelper.SENSUS_CALLBACK_REPEAT_LAG_KEY, false); bool wakeLockReleased = false; // raise callback and notify the user if there is a message. we wouldn't have presented the user with the message yet. serviceHelper.RaiseCallbackAsync(callbackId, repeating, repeatDelayMS, repeatLag, true, // schedule a new callback at the given time. repeatCallbackTime => { serviceHelper.ScheduleCallbackAlarm(serviceHelper.CreateCallbackPendingIntent(intent), callbackId, repeatCallbackTime); }, // if the callback indicates that it's okay for the device to sleep, release the wake lock now. () => { wakeLockReleased = true; serviceHelper.LetDeviceSleep(); serviceHelper.Logger.Log("Wake lock released preemptively for scheduled callback action.", LoggingLevel.Normal, GetType()); }, // release wake lock now if we didn't while the callback action was executing. () => { if (!wakeLockReleased) { serviceHelper.LetDeviceSleep(); serviceHelper.Logger.Log("Wake lock released after scheduled callback action completed.", LoggingLevel.Normal, GetType()); } }); } else { serviceHelper.UnscheduleCallback(callbackId); serviceHelper.LetDeviceSleep(); } } else if (intent.GetStringExtra(SensusServiceHelper.NOTIFICATION_ID_KEY) == SensusServiceHelper.PENDING_SURVEY_NOTIFICATION_ID) { serviceHelper.BringToForeground(); // display the pending scripts page if it is not already on the top of the navigation stack SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() => { IReadOnlyList <Page> navigationStack = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack; Page topPage = navigationStack.Count == 0 ? null : navigationStack.Last(); if (!(topPage is PendingScriptsPage)) { await Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new PendingScriptsPage()); } serviceHelper.LetDeviceSleep(); }); } else { serviceHelper.LetDeviceSleep(); } } else { serviceHelper.LetDeviceSleep(); } }); } return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { Log.Debug("MyNoticeService", "service started!!"); var get_value = intent.GetStringArrayExtra(EXTRA_NAME); appStartTime = DateTime.Parse(get_value[0]); _smtpMailToRaw = get_value[1]; _smtpServer = get_value[2]; _smtpPort = int.Parse(get_value[3]); _smtpAccount = get_value[4]; _smtpPass = get_value[5]; nextNotice = appStartTime.Add(new TimeSpan(8, 15, 0)); //本番用 // nextNotice = appStartTime.Add(new TimeSpan(0, 1, 0)); //テスト用 1分後に通知を出す Log.Debug("MyNoticeService", "next time:" + nextNotice.ToShortTimeString()); morningNoticeDone = false; var t = new System.Threading.Thread(() => { while (true) { //朝の打刻時間バイブ if (!morningNoticeDone && appStartTime.TimeOfDay < DateTime.Now.TimeOfDay && DateTime.Today.DayOfWeek != DayOfWeek.Saturday && DateTime.Today.DayOfWeek != DayOfWeek.Sunday) { //通知実施 try { Vibration.Vibrate(1000); Log.Debug("MyNoticeService", "朝のバイブした"); } catch (FeatureNotSupportedException) { Log.Debug("MyNoticeService", "バイブ失敗"); } //一度通知したらその日は朝の通知を行わないよう、通知実施済みフラグを立てる morningNoticeDone = true; } //日付が変わったら通知実施済みフラグを戻す if (DateTime.Now.TimeOfDay < appStartTime.TimeOfDay) { morningNoticeDone = false; evningDakokuDone = false; } //打刻忘れ通知 if (nextNotice.TimeOfDay < DateTime.Now.TimeOfDay && !evningDakokuDone) { //トースト表示 java.langなスレッドが必要みたい new LooperThread("打刻忘れ??").Start(); Log.Debug("MyNoticeService", "toast表示した"); Console.WriteLine("toast表示した"); //メール送信してみる SendMail(); Log.Debug("MyNoticeService", "打刻忘れ通知のメール送信済み"); try { Vibration.Vibrate(2000); Log.Debug("MyNoticeService", "打刻忘れ通知のバイブした"); } catch (FeatureNotSupportedException) { // バイブしなくても致命的な問題ではないので、例外処理は何もしない Log.Debug("MyNoticeService", "バイブ失敗"); } // 次の通知時刻を設定 if (nextNotice.TimeOfDay < DateTime.Now.TimeOfDay) { //次の通知時間が過去の時刻の場合、現在の時刻にプラス○分する nextNotice = DateTime.Now; } //nextNotice += new TimeSpan(0, 1, 0); //(デバッグ用)1分後 nextNotice += new TimeSpan(1, 0, 0); //1時間後 Log.Debug("MyNoticeService", "notice done!! next ; " + nextNotice.ToShortTimeString()); } System.Threading.Thread.Sleep(5000); } }); t.Start(); //return base.OnStartCommand(intent, flags, startId); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Log.Debug("LogWatcher", "LogWatcher started"); WatchPowerLog(); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { // start your service logic here // Return the correct StartCommandResult for the type of service you are building return(StartCommandResult.NotSticky); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { return(StartCommandResult.RedeliverIntent); }
/** * You should not override this method for your IntentService. Instead, * override {@link #onHandleIntent}, which the system calls when the IntentService * receives a start request. * @see android.app.Service#onStartCommand */ public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { OnStart(intent, startId); return(StartCommandResult.Sticky); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Log.Debug(logTag, "LocationService started"); return(StartCommandResult.Sticky); }
/// <summary> /// The on start command. /// </summary> /// <param name="paramIntent"> /// The param intent. /// </param> /// <param name="flags"> /// The flags. /// </param> /// <param name="startId"> /// The start id. /// </param> /// <returns> /// The Android.App.StartCommandResult. /// </returns> public override StartCommandResult OnStartCommand(Intent paramIntent, StartCommandFlags flags, int startId) { this.OnStart(paramIntent, startId); return(this.redelivery ? StartCommandResult.RedeliverIntent : StartCommandResult.NotSticky); }