在後臺服務中,我使用System.Timers創建一個倒數計時器。爲什麼在我的後臺Service(使用System.Timer)中不會出現Toast通知?
這似乎工作。在控制檯中2秒後,我可以看到Console.WriteLine()打印文本。
然而,Toast通知不出現,我想知道爲什麼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Media;
using Android.Content.Res;
using System.Timers;
namespace AudioTour
{
[Service(Exported = false, Name = "com.AudioTour.AudioService")]
public class AudioService : Service
{
// This method is called to start the Timer
private void StartCountdown()
{
RunTimer(2);
}
private Timer myTimer;
private int countDownSeconds;
// This is my timer
private void RunTimer(int _timerLength)
{
myTimer = new Timer();
myTimer.Interval = 1000;
myTimer.Elapsed += OnTimedEvent;
countDownSeconds = 5;
myTimer.Enabled = true;
}
// When the timer has elapsed this event is called
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs elapsedEventArgs)
{
countDownSeconds--;
// This is what I expect to happen when the timer reaches 0
if (countDownSeconds == 0)
{
Console.WriteLine("Timer Finished");
Toast.MakeText(this, "Timer Finished", ToastLength.Short).Show();
myTimer.Stop();
}
}
謝謝你這麼多的這個答案約克。其中最全面的我有。 – Jim