英文:
what approach should i follow to make Timer service in android
问题
我正在开发一个间隔定时器,它会在每个间隔(例如30分钟)触发警报。
我希望定时器能在后台运行,即使设备处于休眠状态也能发出通知。
有人建议我使用Intent Service,但它已被弃用。我应该使用什么?
- 我希望支持API 21及更低版本。
英文:
I am working on an interval timer which make an alarm every interval (E.g. 30mins).
I want to make the timer work in background or when device is in sleep and show a notification,
I was told to use Intent Service but its deprecated. what should i use?
-I want to support until API 21
答案1
得分: 1
你需要创建一个 BroadcastReceiver
。例如,使用 AlarmManager:
int repeatTime = 30; // 重复闹钟时间(以秒为单位)
AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, processTimerReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 每秒重复一次闹钟
processTimer.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), repeatTime*1000, pendingIntent);
然后创建你的 processTimerReceiver 类:
// 这将每秒调用一次(取决于 repeatTime)
public class processTimerReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// 在每30秒执行一次操作
}
}
记得在 Manifest 中注册:
<receiver android:name="processTimer">
<intent-filter>
<action android:name="processTimerReceiver">
</action>
</intent-filter>
</receiver>
编辑:
如果你的应用使用互联网连接,你可以使用 Firebase 每30分钟发送一次通知。
英文:
You need to create a BroadcastReceiver
. For example, using AlarmManager:
int repeatTime = 30; //Repeat alarm time in seconds
AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, processTimerReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
//Repeat alarm every second
processTimer.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),repeatTime*1000, pendingIntent);
And create your processTimerReciever class:
//This is called every second (depends on repeatTime)
public class processTimerReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//Do something every 30 seconds
}
}
Remember to register into Manifest:
<receiver android:name="processTimer" >
<intent-filter>
<action android:name="processTimerReceiver" >
</action>
</intent-filter>
</receiver>
EDIT:
If your app use an internet connection, you can send every 30 mins a notification using Firebase
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论