我应该遵循什么方法在 android 中制作定时器服务
what approach should i follow to make Timer service in android
我正在开发一个间隔计时器,它每隔一段时间(例如 30 分钟)发出一次警报。
我想让计时器在后台或设备处于睡眠状态时工作并显示通知,
有人告诉我使用 Intent Service 但它已被弃用。我应该用什么?
-我要支持到API 21
您需要创建一个 BroadcastReceiver
。例如,使用 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);
并创建您的 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
}
}
记得注册到Manifest:
<receiver android:name="processTimer" >
<intent-filter>
<action android:name="processTimerReceiver" >
</action>
</intent-filter>
</receiver>
编辑:
如果您的应用使用互联网连接,您可以使用 Firebase 每 30 分钟发送一次通知
我正在开发一个间隔计时器,它每隔一段时间(例如 30 分钟)发出一次警报。 我想让计时器在后台或设备处于睡眠状态时工作并显示通知, 有人告诉我使用 Intent Service 但它已被弃用。我应该用什么? -我要支持到API 21
您需要创建一个 BroadcastReceiver
。例如,使用 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);
并创建您的 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
}
}
记得注册到Manifest:
<receiver android:name="processTimer" >
<intent-filter>
<action android:name="processTimerReceiver" >
</action>
</intent-filter>
</receiver>
编辑:
如果您的应用使用互联网连接,您可以使用 Firebase 每 30 分钟发送一次通知