我想每隔一小时(例如)重复一个函数(或任何动作),即使应用程序没有运行。
我已经创建了一个演示项目,所以你可以看看它:
https://github.com/joancolmenerodev/BroadcastReceiverAndAlarmManagerInKotlin
首先你必须创建一个BroadcastReceiver
,然后使用AlarmManager
你可以决定你想要被调用的时间间隔。
创建一个BroadcastReceiver
你可以这样做:
val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
toast("This toast will be shown every X minutes")
}
}
然后你有这个方法来开始工作:
val mIntent = Intent(context, broadCastReceiver)
val mPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, mIntent, 0)
val mAlarmManager = context
.getSystemService(Context.ALARM_SERVICE) as AlarmManager
mAlarmManager.setRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(),
CHANGETOYOURDESIREDSECONDS, mPendingIntent
)
然后,即使应用程序关闭,您也可以看到Toast。
你可以使用BroadcastReceiver
注册你的context.registerReceiver(receiver, IntentFilter("something"))
,然后添加到mIntent
和“某事”的行动。
如果您不喜欢这种方式,可以创建一个名为MyReceiver
的新类,它扩展BradcastReceiver
,如下所示:
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context,"This toast will be shown every X minutes", Toast.LENGTH_SHORT).show()
}
}
然后启动警报执行此操作:
val mIntent = Intent(this,MyReceiver :: class.java)
val mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val mAlarmManager = this
.getSystemService(Context.ALARM_SERVICE) as AlarmManager
mAlarmManager.setRepeating(
AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
WHATEVERYOUWANT, mPendingIntent
)
注意:默认设置为60000
从Android 5.1开始,价值将被强制为60000;不要依赖于这一点
如果您使用的是AndroidX(JetPack)库,请考虑使用qazxsw poi
简单的例子:
Workmanager
从这样开始,每小时完成你的工作:
public class MyWorker extends Worker {
static final String TAG = "workmng";
@NonNull
@Override
public WorkerResult doWork() {
Log.d(TAG, "doWork: start");
//Do your job here
Log.d(TAG, "doWork: end");
return WorkerResult.SUCCESS;
}
}
添加应用程序gradle文件:
PeriodicWorkRequest myWorkRequest = new PeriodicWorkRequest.Builder(MyWorker.class, 60, TimeUnit.MINUTES)
.build();