Reputation: 594
I am developing an app that will play certain sound at 9:15AM
and 10:30AM
in the morning,
I am done with playing the sound part already but I am facing issues while monitoring the current android system time.
Here is what I am doing,
I have an array where 9:15AM and 10:30AM are stored as String. While I am using Java Calendar class to get current time of the System,
Calendar cTime = Calendar.getInstance();
public String currentTime() {
String hour = cTime.get(Calendar.HOUR) + "";
String mins = cTime.get(Calendar.MINUTE) + "";
return hour+""+mins+"AM";
}
and I am playing the sound using this code,
public void playSound() {
MediaPlayer player = MediaPlayer.create(this, R.raw.s);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
The problem is,
If it is 9:15AM in the morning and I run the app then the app would play the sound, or if it is 10:30 in the morning and I run the app then App will play the sound, but this isn't what I want, I want my app to keep monitoring the time all the time and when its 9:15AM or 10:30AM, the sound should play regardless of the app is running or not.
i tried one approach by comparing the current time with 10:30AM or 9:30AM in a while loop, but it hangs my phone and this seems ugly idea. I couldn't think of any other way to monitor the time, please suggest me something.
Upvotes: 1
Views: 119
Reputation: 466
I think you should try these codes ( Android apis)
Use AlarmManager class to schedule and execute actions/operations that you want to perform regardless of the status of your android application whether it's running or not.
But before applying this concept you you should go through more details about this class , as it provides two types of alarm Elapsed Realtime and Real Time Clock..
and you will have to use BroadcastReceiver to receive the Intent .
if you want to use loops the you should use following codes(better than java calendar classes)
Time t = new Time(); t.setToNow();
or more better codes will be because now you will get current time zone of your user , so here you go;
Time t = new Time(Time.getCurrentTimezone()); t .setToNow();
Upvotes: 0
Reputation: 1007296
Use AlarmManager
to schedule to get control at those points in time.
Upvotes: 4