即使应用未运行,我也希望每隔一小时(例如)重复一次功能(或任何操作)。
答案 0 :(得分:0)
我已经创建了一个演示项目,所以您可以看一下它:
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(这是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;不要完全依赖
答案 1 :(得分:0)
如果您使用的是AndroidX(JetPack)库,请考虑使用Workmanager
简单的例子:
v-for
开始这样,每小时做一次工作:
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();