如何使用Kotlin在Android Studio中每小时重复一次功能?

时间:2019-03-26 18:05:53

标签: android kotlin alarmmanager repeat

即使应用未运行,我也希望每隔一小时(例如)重复一次功能(或任何操作)。

2 个答案:

答案 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();