使用闹钟管理器在特定时间

huangapple go评论80阅读模式
英文:

Using Alarm Manager at specific time

问题

Sure, here's the translated content:

我需要在印度标准时间晚上11点59分通过设置AlarmManager来触发一段代码。

有人可以给我展示如何在安卓中使用AlarmManager的示例代码吗?

我已经尝试了一些代码几天了,但它就是不起作用。

英文:

I need to trigger a block of code at 11:59 pm IST from the AlarmManager being set.

Can someone show me sample code on how to use an AlarmManager in ِAndroid?

I have been playing around with some code for a few days and it just won't work.

答案1

得分: 1

这是一个使用 AlarmManager 的示例代码,您需要根据自己的需求更改日期和时间。我将其设置为今天的 23:59。

// 当闹钟触发时要启动的待处理意图。在这种情况下,打开 AlarmActivity
Intent intent = new Intent(getApplicationContext(), AlarmActivity.class);
PendingIntent alarmIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

// 将闹钟设置为今天的 23:59
calendar = Calendar.getInstance(TimeZone.getTimeZone("IST"));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(),
        alarmIntent);

在给定的日期和时间,意图将被触发,因此您需要在 AlarmActivity 中编写逻辑。您还可以将意图更改为启动服务或触发广播消息。

英文:

Here's a sample code of using the AlarmManager, you will need to change date and time according to your needs. I put it for today at 23:59

// Pending intent to be fired when alarm occurrs. In this case, open the AlarmActivity
Intent intent = new Intent(getApplicationContext(), AlarmActivity.class);
PendingIntent alarmIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

// Set the alarm for today at 23:59
calendar = Calendar.getInstance(TimeZone.getTimeZone("IST"));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(),
        alarmIntent);

In the given date-time the Intent will be fired so you need to make you logic in the AlarmActivity. You could also change the intent to start a Service or fire a Broadcast message

huangapple
  • 本文由 发表于 2020年4月5日 19:43:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61042036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定