android 中的定时任务

android中经常会遇到要做一些定时任务,使用android系统的TIME_TICK广播可以很方便的完成需求,TIME_TICK的使用:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {


        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                //在这里我们可以获取到当前的系统时间与定时任务开始结束时间做对比,并执行相应的定时任务
                Log.e(TAG, "onReceive:ACTION_TIME_TICK ");
            } else if (intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
                Log.e(TAG, "onReceive:ACTION_TIME_CHANGED ");
            }
        }
};

注册:

 IntentFilter filter = new IntentFilter();
 filter.addAction(Intent.ACTION_TIME_TICK);
 filter.addAction(Intent.ACTION_TIME_CHANGED);
 registerReceiver(broadcastReceiver, filter);

TIME_TICK广播的注册必须使用动态注册,并且一定要记得使用完之后取消注册:

unregisterReceiver(broadcastReceiver);
补充:TIME_TICK每分钟触发一次,在使用中如果对时间的要求比较苛刻可以使用Timer或者是java中的
ScheduledExecutorService实现

猜你喜欢

转载自blog.csdn.net/coward_/article/details/81061707