Android——定时器轮询
Posted Yawn__
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android——定时器轮询相关的知识,希望对你有一定的参考价值。
文章目录
1. Executor
- kotlin
fun mExecutor()
val executor: ScheduledExecutorService = Executors.newScheduledThreadPool(1)
executor.scheduleWithFixedDelay(
object : Runnable
override fun run()
runOnUiThread
//todo
, 0, 60, TimeUnit.SECONDS)
- java
public void mExecutor()
mScheduledExecutorService = new ScheduledThreadPoolExecutor(1);
mScheduledExecutorService.scheduleAtFixedRate(new Runnable()
@Override
public void run()
//todo
, 0, 60, TimeUnit.SECONDS);
2. Handler
- kotlin
fun mHandler()
val mTimeCounterRunnable : Runnable = object : Runnable
override fun run()
runOnUiThread
//todo
mHandler.postDelayed(this, (60*1000).toLong())
mTimeCounterRunnable.run()
- java
private final Handler mTimeHandler = new Handler(Looper.getMainLooper());
private Runnable mTimeCounterRunnable = new Runnable()
@Override
public void run()
//todo
mTimeHandler.postDelayed(this, 15 * 60 * 1000);
;
public void meHandler()
mTimeCounterRunnable.run();
3. Timer
- kotlin
private var mTimer: Timer? = null
private var mTimerTask: TimerTask? = null
fun mTimer()
mTimer = Timer()
mTimerTask = object : TimerTask()
override fun run()
runOnUiThread
//todo
mTimer!!.schedule(mTimerTask, 0, 60 * 1000)
- java
private Timer mTimer;
private TimerTask mTimerTask;
public void mTimer()
mTimer = new Timer();
mTimerTask = new TimerTask()
@Override
public void run()
//todo
;
mTimer.schedule(mTimerTask,0, 15 * 60 * 1000);
4. AlarmManager
- kotlin
private val ActionName = "ActionName"
private fun mAlarmManager()
registerBoradcastReceiver()
//start AlarmManager
val intent = Intent(ActionName)
var sender : PendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT)
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE)
else
sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT)
*/
var bleScanReceive : BleScanReceiver = BleScanReceiver()
val firstime = SystemClock.elapsedRealtime()
val am = getSystemService(ALARM_SERVICE) as AlarmManager
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5000, sender )
fun registerBoradcastReceiver()
val myIntentFilter = IntentFilter()
myIntentFilter.addAction(ActionName)
registerReceiver(mBroadcastReceiver, myIntentFilter)
private val mBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver()
override fun onReceive(context: Context, intent: Intent)
val action = intent.action
if (action == ActionName)
//todo
- java
public final static String ActionName = "ActionName";
public BroadcastReceiver mBleReceiver;
public void realTimeAlarmManager()
// Register Bluetooth message broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction(ActionName );
mBleReceiver = new BleReceiver();
mContext.registerReceiver(mBleReceiver, filter);
// AlarmManager
AlarmManager manager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
/*Intent intent = new Intent();
intent.setAction(ACTION_realTimeAlarmManager);
PendingIntent sender;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
else
sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
*/
PendingIntent sender;
Intent intent = new Intent();
intent.setAction("com.example.testApp.test_FOUND");
intent.setPackage("com.example.testApp");
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sender = PendingIntent.getBroadcast(mContext, 1213, intent,PendingIntent.FLAG_MUTABLE| PendingIntent.FLAG_CANCEL_CURRENT);
long triggerAtTime = SystemClock.elapsedRealtime();
manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtTime, 15 * 60 * 1000, sender);
public class BleReceiver extends BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent)
String action = intent.getAction();
if (TextUtils.isEmpty(action))
return;
switch (action)
case ActionName :
//todo
default:
break;
4. WorkManager ( kotlin)
- 配置build.gradle(app):
dependencies
implementation("androidx.work:work-runtime:2.7.1")
- 定义任务: RealTimeWorker
package com.example.testApp
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
class RealTimeWorker (appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams)
val mContext : Context = appContext
override fun doWork(): Result
try
//todo
return Result.success()
catch (exception: Exception)
Log.e("realTimeWorker", "Error cleaning up", exception)
return Result.failure()
- 简单使用:
private fun mWorkanager()
// Once-Run
var continuation = WorkManager.getInstance(mContext)
// Task identity + job requirements of the task + task to be executed (actually support task chain)
.beginUniqueWork("realTimeWorkManager", ExistingWorkPolicy.REPLACE, OneTimeWorkRequest.from(RealTimeWorker::class.java))
continuation.enqueue()
// Repeated-Run
val workRequest = PeriodicWorkRequest.Builder(RealTimeWorker::class.java, MIN_PERIODIC_INTERVAL_MILLIS,TimeUnit.MILLISECONDS).build();
WorkManager.getInstance().enqueue(workRequest);
以上是关于Android——定时器轮询的主要内容,如果未能解决你的问题,请参考以下文章