什么方法应该在安卓中使用以创建计时器服务

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

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:

&lt;receiver android:name=&quot;processTimer&quot; &gt;
   &lt;intent-filter&gt;
       &lt;action android:name=&quot;processTimerReceiver&quot; &gt;
       &lt;/action&gt;
   &lt;/intent-filter&gt;
&lt;/receiver&gt;

EDIT:

If your app use an internet connection, you can send every 30 mins a notification using Firebase

huangapple
  • 本文由 发表于 2020年10月6日 16:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64222157.html
匿名

发表评论

匿名网友

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

确定