Issue
My alarm project is almost complete and i have code that compares current time and target time every second to see if true and play ringtone on the event that the Alarm matures. My problem is i can't seem to be able to play the ringtone for a specified period of time and then stop Here is my Source File...
class SecondActivity : AppCompatActivity{
//System Timer defintion with interval of one second in class
System.Timers.Timer _stopringtone = new System.Timers.Timer(1000);
protected override void OnCreate(Bundle savedInstanceState){
//Defining path for Ringtone's default uri
path = RingtoneManager.GetDefaultUri(RingtoneType.Ringtone);
//Ringtone instance
r = RingtoneManager.GetRingtone(Application.Context, path);
//Timer elpase event handler
_stopringtone.Elapsed += _stopringtone_Elapsed;
//Timer disabled by default will be enabled by alarm maturity event
_stopringtone.Enabled = false;
}
//This event checks every second if the two time variables are equal and plays a ringtone alongside a vibration pattern
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
RunOnUiThread(() =>
{
//Code to check current time and target time defined here
//Logic to compare the two variables
if (span == span1){
//Event Elapse method returns true so alarm time has matured, play some music and vibration
//Vibration definition
Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
//Vibration pattern definition
long[] pattern = { 0, 2000, 2000 };
//Play vibration
vibrator.Vibrate(pattern,0);
//Play Ringtone Uri,This is where I need code to play the ringtone for interval 60 seconds
r.Play();
//Alarm matured so enable timer to count down 20 seconds and shut off music
_stopringtone.Enabled = true;
}
}
//CountDown Logic method
private void _stopringtone_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
RunOnUiThread(() =>
{
int a = 0;
int b = a++;
if (b == 10)
{
r.Stop();
}
});
}
}
Ringtone plays forever,i need some code to check in and manage the playback time thanks. It works now...
Solution
You could use TimerTask
and Timer
to schedule a specified period of time to do something.
For example , create a TimerTask each second to count and stop timer task until 60 seconds.
class MyTask : TimerTask
{
Timer mTimer;
Ringtone ringtone;
MainActivity mainActivity;
public MyTask(Timer timer, Ringtone r, MainActivity mainActivity)
{
this.mTimer = timer;
this.ringtone = r;
this.mainActivity = mainActivity;
}
int i;
public override void Run()
{
if (i < 60)
{
i++;
}
else
{
mTimer.Cancel();
ringtone.Stop();
mainActivity.StartActivity(typeof(NextActivity));
}
}
}
Then in Activity.cs, we can invoke Ringtone.Play()
in a method, such as a button clicked method:
private void Button_Click(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Schedule(new MyTask(timer,r,this), 0, 1000);
r.Play();
}
Answered By - Junior Jiang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.