Kotlin实现定时任务(AlarmManager + BroadcastReceiver)

2023-06-01 10:14:01 买帖  | 投诉/举报

篇首语:本文由小编为大家整理,主要介绍了Kotlin实现定时任务(AlarmManager + BroadcastReceiver)相关的知识,希望对你有一定的参考价值。

前言

android实现定时任务有很多种方式,为什么选择了AlarmManager + BroadcastReceiver呢?
因为AlarmManager系统级别的闹钟服务,如果你的项目存在长时间在后台运行的定时任务,因为Android设备有自己的休眠策略,当长时间的无操作,设备会自动让CPU进入 休眠状态,这样就可能导致Timer中的定时任务无法正常运行!而AlarmManager不存在这种情况,因为AlarmManager具有唤醒CPU的功能可以保证每次需要执行特定任务时CPU都能正常工作

正因如此,我将AlarmManager + BroadcastReceiver封装成一个TimeTask,可直接复制使用。

TimeTask.kt

增加权限~~

<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
class TimeTask<T : TimeTask.Task?>(context: Context, actionName: String, task: T)     private var mContext: Context?    private val mActionName: String    private var mReceiver: TimeTaskReceiver? = null    private val mTask: T?    companion object         private var mPendingIntent: PendingIntent? = null        init         mContext = context        mActionName = actionName        mTask = task        initReceiver(context, actionName)        fun startLooperTask()         if (null != mTask)             mTask.exeTask()            configureAlarmManager(mTask.period())                fun stopLooperTask()         cancelAlarmManager()        fun onClose()         mContext!!.unregisterReceiver(mReceiver)        mContext = null        @SuppressLint("ObsoleteSdkInt")    private fun configureAlarmManager(time: Long)         val manager = mContext!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager        val pendIntent = pendingIntent        when             Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ->                 manager.setExactAndAllowWhileIdle(                    AlarmManager.ELAPSED_REALTIME_WAKEUP,                    SystemClock.elapsedRealtime() + time,                    pendIntent                )                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ->                 manager.setExact(                    AlarmManager.ELAPSED_REALTIME_WAKEUP,                    SystemClock.elapsedRealtime() + time,                    pendIntent                )                        else ->                 manager[AlarmManager.ELAPSED_REALTIME_WAKEUP,                        SystemClock.elapsedRealtime() + time] = pendIntent                            @get:SuppressLint("UnspecifiedImmutableFlag")    private val pendingIntent: PendingIntent?        get()             if (mPendingIntent == null)                 val requestCode = 0                val intent = Intent()                intent.action = mActionName                when                     Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->                         mPendingIntent = PendingIntent.getBroadcast(                            mContext, requestCode, intent,                            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE                        )                                        else ->                         mPendingIntent = PendingIntent.getBroadcast(                            mContext,                            requestCode,                            intent,                            PendingIntent.FLAG_UPDATE_CURRENT                        )                                                            return mPendingIntent            private fun cancelAlarmManager()         val manager = mContext!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager        manager.cancel(pendingIntent)        private fun initReceiver(context: Context, actionName: String)         mReceiver = TimeTaskReceiver()        val intentFilter = IntentFilter()        intentFilter.addAction(actionName)        context.registerReceiver(mReceiver, intentFilter)        internal inner class TimeTaskReceiver : BroadcastReceiver()         override fun onReceive(context: Context, intent: Intent)             startLooperTask()                interface Task         fun period(): Long             // 默认时间5S            return 5000L                fun exeTask()    

使用方式

//比如在Activity中class GatewayActivity : AppCompatActivity()     private lateinit var tt : TimeTask<TimeTask.Task>    override fun onCreate(savedInstanceState: Bundle?)         super.onCreate(savedInstanceState)        setContentView(R.layout.activity_gateway)        tt = TimeTask(this, "abc", object : TimeTask.Task             override fun exeTask()                 LogUtils.debugInfo("exeTask>>>>>>>>>>>>")                    )        findViewById<TextView>(R.id.tv).setOnClickListener             tt.startLooperTask()                findViewById<TextView>(R.id.tvs).setOnClickListener             tt.stopLooperTask()                override fun onDestroy()         super.onDestroy()        tt.onClose()    

注意!!!
如果需要修改定时任务的时间间隔,可以重写TimeTask.Task中的period()方法:

        tt = TimeTask(this, "abc", object : TimeTask.Task             // 从API 19开始,最小执行时间是5S,如果小于5S,则设置无效,还是按照5S周期执行            override fun period(): Long                 return 10000L                        override fun exeTask()                 LogUtils.debugInfo("exeTask>>>>>>>>>>>>")                    )

日志打印,Android 9 & Android 12测试输出:

2022-05-03 13:46:26.188 22817-22817/com.jon.gateway D/JetpackMvvm: exeTask>>>>>>>>>>>>2022-05-03 13:46:36.224 22817-22817/com.jon.gateway D/JetpackMvvm: exeTask>>>>>>>>>>>>2022-05-03 13:46:46.244 22817-22817/com.jon.gateway D/JetpackMvvm: exeTask>>>>>>>>>>>>2022-05-03 13:46:56.256 22817-22817/com.jon.gateway D/JetpackMvvm: exeTask>>>>>>>>>>>>2022-05-03 13:47:06.270 22817-22817/com.jon.gateway D/JetpackMvvm: exeTask>>>>>>>>>>>>2022-05-03 13:47:16.283 22817-22817/com.jon.gateway D/JetpackMvvm: exeTask>>>>>>>>>>>>

非常感谢你能看到最后,如果能够帮助到你,是我的荣幸!

以上是关于Kotlin实现定时任务(AlarmManager + BroadcastReceiver)的主要内容,如果未能解决你的问题,请参考以下文章