Я использую Dispatcher.StartTimer для запуска таймера каждые 1 секунду, как показано ниже:
Dispatcher.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if ((time == "00:00" )
{
//cancel activities
}
else
{
//doing some activities
}
return timerValue; // Continue or stop the timer
});
В Android все работает нормально, но в iOS возникают некоторые проблемы. В переднем режиме iOS оно работает нормально, но если мы оставим приложение в фоновом режиме после запуска таймера, блок if приведенного выше кода не работает.
Мне нужно выполнить некоторые действия. когда время 00:00, и оно работает нормально, когда приложение открыто. Что произойдет, если мы оставим приложение в фоновом режиме, и как можно исправить подобные проблемы?
Обновленный код:
public void StartTimer()
{
try
{
// Start service for Watch Me starting
isWatchMeStart = true;
timer = new Stopwatch();
timer.Start();
SetTimer();
string instanceId = "";
isWatchMeLocationStart = true;
Debug.WriteLine("iswatchmerunning localdb value:>>" + Preferences.Default.Get("iswatchmerunning", false));
if (!Preferences.Default.Get("iswatchmerunning", false))
{
StartWatchMeService(instanceId);
}
else
{
bool isInitial = true;
Dispatcher.StartTimer(new TimeSpan(0, 0, 10), () =>
{
if (isWatchMeLocationStart)
{
if (Preferences.Default.Get("islogin", "") != "false")
{
string triggerType;
if (isInitial)
{
isInitial = false;
triggerType = "WATCHME";
}
else
{
//triggerType = "duplicate";
triggerType = "WATCHME";
}
string emergencyTriggered = "";
if (pendingTime == "00:00")
{
//emergencyTriggered = "true";
emergencyTriggered = "false";
}
else
{
emergencyTriggered = "false";
}
Task.Run(async () => SaveUserLocationDetails(triggerType, emergencyTriggered, Preferences.Default.Get("watchmeinstanceId", "")));
}
else
{
isWatchMeLocationStart = false;
}
}
return isWatchMeLocationStart;
});
cancel_watchme_button.IsVisible = true;
cancel_watchme_button.BackgroundColor = Color.FromArgb("#1c98d7");
cancel_watchme_button.TextColor = Colors.White;
hpvm.isWatchmeStarted = true;
isSlidingActivitiesStarted = true;
Preferences.Default.Set("iswatchmerunning", true);
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception:>>" + ex);
}
}
private Task SetTimer()
{
_timer = new System.Timers.Timer(1000); // 1000ms = 1 second
_timer.AutoReset = true; // Set AutoReset to true to keep the timer running
_timer.Elapsed += OnTimerElapsed;
_timer.Enabled = true; // Start the timer immediately
return Task.CompletedTask; // Return a completed task
}
private async void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
await Dispatcher.DispatchAsync(() =>
{
hpvm.InputTransparent = false;
string slidertime = slider_timer_label.Text;
Debug.WriteLine("slidertime:>>" + slidertime);
//if(slidertime == "00:10")
//{
// slidertime = ":10:23";
//}
int colonCount = slidertime.Count(c => c == ':');
if ((slidertime.Trim() == "00:00" || colonCount > 1) && hpvm.isWatchmeStarted)
{
// Cancel WatchMe feature
timerValue = false;
isWatchMeStart = false;
cancel_watchme_button.BackgroundColor = Colors.White;
cancel_watchme_button.TextColor = Colors.Black;
cancel_watchme_button.IsVisible = false;
slider_timer_label.TextColor = Color.FromArgb("#ededed");
slider_timer_label.BackgroundColor = Color.FromArgb("#ededed");
watchme_slider.Value = 0; // Reset slider
StartSOSBlink();
isInstancetriggered = true;
}
else
{
if (!isWatchMeCanceled)
{
// Calculate remaining time
TimeSpan ts = timer.Elapsed;
string newTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
var remainingTime = watchMeTime - TimeSpan.Parse(newTime);
//Debug.WriteLine("newTime:>>" + newTime);
//Debug.WriteLine("watchMeTime:>>" + watchMeTime);
//Debug.WriteLine("remainingTime:>>" + remainingTime);
string[] time = remainingTime.ToString().Split('.');
string result = time[0].Substring(3); // Format remaining time (mm:ss)
pendingTime = result;
if (!hpvm.isDragInProgress)
{
hpvm.preValue = watchme_slider.Value;
}
//Debug.WriteLine("result:>>" + result);
try
{
string[] timeParts = result.Split(':');
int minutes = int.Parse(timeParts[0]);
int seconds = int.Parse(timeParts[1]);
hpvm.pendingTimeInSeconds = (minutes * 60) + seconds;
}
catch (Exception ex)
{
Debug.WriteLine("exception:>>" + ex);
}
// Prevent triggering the SliderValueChanged event
isProgrammaticChange = true; // Set flag to skip event handling
if (!hpvm.isDragInProgress)
{
watchme_slider.Value = remainingTime.TotalMinutes / 60; // Update slider value
}
isProgrammaticChange = false; // Reset flag
watchme_timer_label.Text = "Watch Me emergency will be triggered in " + result + " minutes";
slider_timer_label.Text = result;
//for live slider on top
double thumbWidth = 20; // Approximate width of the thumb (adjust this value based on your ThumbImageSource size)
double adjustedValue = watchme_slider.Value * ((watchme_slider.Width - thumbWidth) / watchme_slider.Maximum);
if (!hpvm.isDragInProgress)
{
slider_timer_label.TranslateTo(adjustedValue + (thumbWidth / 2), 0, 100);
slider_extension_timer_label.TranslateTo(adjustedValue + (thumbWidth / 2), 0, 100);
}
timerValue = isWatchMeStart;
if (isSOSActivated && !isWatchMeStart)
{
watchme_timer_label.TextColor = Colors.Black;
watchme_timer_label.Text = "You can't activate the WatchMe now since the SOS is already activated.";
}
}
else
{
timerValue = false;
// Stop and dispose the timer when the page disappears
if (_timer != null)
{
_timer.Stop();
_timer.Elapsed -= OnTimerElapsed;
_timer.Dispose();
}
}
//return timerValue; // Continue or stop the timer
}
});
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... app-in-bac
MAUI: Dispatcher.StartTimer не работает на iPhone, когда приложение работает в фоновом режиме ⇐ C#
Место общения программистов C#
1736544952
Anonymous
Я использую Dispatcher.StartTimer для запуска таймера каждые 1 секунду, как показано ниже:
Dispatcher.StartTimer(new TimeSpan(0, 0, 1), () =>
{
if ((time == "00:00" )
{
//cancel activities
}
else
{
//doing some activities
}
return timerValue; // Continue or stop the timer
});
В Android все работает нормально, но в iOS возникают некоторые проблемы. В переднем режиме iOS оно работает нормально, но если мы оставим приложение в фоновом режиме после запуска таймера, блок if приведенного выше кода не работает.
Мне нужно выполнить некоторые действия. когда время 00:00, и оно работает нормально, когда приложение открыто. Что произойдет, если мы оставим приложение в фоновом режиме, и как можно исправить подобные проблемы?
[b]Обновленный код:[/b]
public void StartTimer()
{
try
{
// Start service for Watch Me starting
isWatchMeStart = true;
timer = new Stopwatch();
timer.Start();
SetTimer();
string instanceId = "";
isWatchMeLocationStart = true;
Debug.WriteLine("iswatchmerunning localdb value:>>" + Preferences.Default.Get("iswatchmerunning", false));
if (!Preferences.Default.Get("iswatchmerunning", false))
{
StartWatchMeService(instanceId);
}
else
{
bool isInitial = true;
Dispatcher.StartTimer(new TimeSpan(0, 0, 10), () =>
{
if (isWatchMeLocationStart)
{
if (Preferences.Default.Get("islogin", "") != "false")
{
string triggerType;
if (isInitial)
{
isInitial = false;
triggerType = "WATCHME";
}
else
{
//triggerType = "duplicate";
triggerType = "WATCHME";
}
string emergencyTriggered = "";
if (pendingTime == "00:00")
{
//emergencyTriggered = "true";
emergencyTriggered = "false";
}
else
{
emergencyTriggered = "false";
}
Task.Run(async () => SaveUserLocationDetails(triggerType, emergencyTriggered, Preferences.Default.Get("watchmeinstanceId", "")));
}
else
{
isWatchMeLocationStart = false;
}
}
return isWatchMeLocationStart;
});
cancel_watchme_button.IsVisible = true;
cancel_watchme_button.BackgroundColor = Color.FromArgb("#1c98d7");
cancel_watchme_button.TextColor = Colors.White;
hpvm.isWatchmeStarted = true;
isSlidingActivitiesStarted = true;
Preferences.Default.Set("iswatchmerunning", true);
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception:>>" + ex);
}
}
private Task SetTimer()
{
_timer = new System.Timers.Timer(1000); // 1000ms = 1 second
_timer.AutoReset = true; // Set AutoReset to true to keep the timer running
_timer.Elapsed += OnTimerElapsed;
_timer.Enabled = true; // Start the timer immediately
return Task.CompletedTask; // Return a completed task
}
private async void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
await Dispatcher.DispatchAsync(() =>
{
hpvm.InputTransparent = false;
string slidertime = slider_timer_label.Text;
Debug.WriteLine("slidertime:>>" + slidertime);
//if(slidertime == "00:10")
//{
// slidertime = ":10:23";
//}
int colonCount = slidertime.Count(c => c == ':');
if ((slidertime.Trim() == "00:00" || colonCount > 1) && hpvm.isWatchmeStarted)
{
// Cancel WatchMe feature
timerValue = false;
isWatchMeStart = false;
cancel_watchme_button.BackgroundColor = Colors.White;
cancel_watchme_button.TextColor = Colors.Black;
cancel_watchme_button.IsVisible = false;
slider_timer_label.TextColor = Color.FromArgb("#ededed");
slider_timer_label.BackgroundColor = Color.FromArgb("#ededed");
watchme_slider.Value = 0; // Reset slider
StartSOSBlink();
isInstancetriggered = true;
}
else
{
if (!isWatchMeCanceled)
{
// Calculate remaining time
TimeSpan ts = timer.Elapsed;
string newTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
var remainingTime = watchMeTime - TimeSpan.Parse(newTime);
//Debug.WriteLine("newTime:>>" + newTime);
//Debug.WriteLine("watchMeTime:>>" + watchMeTime);
//Debug.WriteLine("remainingTime:>>" + remainingTime);
string[] time = remainingTime.ToString().Split('.');
string result = time[0].Substring(3); // Format remaining time (mm:ss)
pendingTime = result;
if (!hpvm.isDragInProgress)
{
hpvm.preValue = watchme_slider.Value;
}
//Debug.WriteLine("result:>>" + result);
try
{
string[] timeParts = result.Split(':');
int minutes = int.Parse(timeParts[0]);
int seconds = int.Parse(timeParts[1]);
hpvm.pendingTimeInSeconds = (minutes * 60) + seconds;
}
catch (Exception ex)
{
Debug.WriteLine("exception:>>" + ex);
}
// Prevent triggering the SliderValueChanged event
isProgrammaticChange = true; // Set flag to skip event handling
if (!hpvm.isDragInProgress)
{
watchme_slider.Value = remainingTime.TotalMinutes / 60; // Update slider value
}
isProgrammaticChange = false; // Reset flag
watchme_timer_label.Text = "Watch Me emergency will be triggered in " + result + " minutes";
slider_timer_label.Text = result;
//for live slider on top
double thumbWidth = 20; // Approximate width of the thumb (adjust this value based on your ThumbImageSource size)
double adjustedValue = watchme_slider.Value * ((watchme_slider.Width - thumbWidth) / watchme_slider.Maximum);
if (!hpvm.isDragInProgress)
{
slider_timer_label.TranslateTo(adjustedValue + (thumbWidth / 2), 0, 100);
slider_extension_timer_label.TranslateTo(adjustedValue + (thumbWidth / 2), 0, 100);
}
timerValue = isWatchMeStart;
if (isSOSActivated && !isWatchMeStart)
{
watchme_timer_label.TextColor = Colors.Black;
watchme_timer_label.Text = "You can't activate the WatchMe now since the SOS is already activated.";
}
}
else
{
timerValue = false;
// Stop and dispose the timer when the page disappears
if (_timer != null)
{
_timer.Stop();
_timer.Elapsed -= OnTimerElapsed;
_timer.Dispose();
}
}
//return timerValue; // Continue or stop the timer
}
});
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79333267/maui-dispatcher-starttimer-is-not-working-in-iphone-when-keeping-the-app-in-bac[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия