我正在尝试构建一个应用程序,我正在为特定的日期和时间构建倒数计时器。现在我使用android倒计时器类构建了倒数计时器,它正常工作。
现在我要做的是在onFinish()
的{{1}}中显示一个通知方法,说明事件已经到达。即使应用程序没有运行,我也希望显示通知。到目前为止,这是我的代码:
Countdown Timer
倒数计时器结束后如何显示通知。即使应用程序可能无法运行。我见过 new CountDownTimer(timer.getIntervalMillis(), 1000) {
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
int days = (int) ((millisUntilFinished / 1000) / 86400);
int hours = (int) (((millisUntilFinished / 1000) - (days * 86400)) / 3600);
int minutes = (int) (((millisUntilFinished / 1000)
- (days * 86400) - (hours * 3600)) / 60);
int seconds = (int) ((millisUntilFinished / 1000) % 60);
String countdown = String.format("%02d:%02d:%02d:%02d", days,
hours, minutes, seconds);
countdownTimer.setText(countdown);
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
countdownBegins.setVisibility(View.GONE);
countdownTimer.setText("SYMAGINE IS HERE!!");
}
}.start();
但不知怎的,我不理解它。由于我是一个新手,所以我可以通过适当的解释来获得帮助。
答案 0 :(得分:3)
你应该使用android AlarmManager。当你使用它来解决警报时,它会触发事件(无论你的应用程序是否正在运行,它都会触发事件)。
由于您要显示通知,我建议您在警报触发时启动服务,并从服务构建通知。
看看这个:http://www.techrepublic.com/blog/software-engineer/use-androids-alarmmanager-to-schedule-an-event/
以下是一个示例:How to start Service using Alarm Manager in Android? - >它使用重复警报,但逻辑是一样的。
尝试一些示例,您将掌握它,AlarmManager实际上非常简单易用,您将从上面的示例中看到。
贝娄的例子来自:How to schedule a task using Alarm Manager
public void scheduleAlarm(View V)
{
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
Intent intentAlarm = new Intent(this, AlarmReciever.class);
//Get the Alarm Service
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
}
AlarmReciever Class
public class AlarmReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
// Your Code When Alarm will trigger
}
}