Java +安卓 定时任务

1.android 自带闹钟定时任务

安卓闹钟可以配合广播来实现(不推荐),系统资源浪费,安卓系统在5.0以后的定时
任务貌似触发时间不准了,因为了为了省电。

//获取系统闹钟
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(ReportDetailsActivity.this, ReportDetailsActivity.MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
//开启定时任务
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, 5 * 1000, pendingIntent);

记得在manifeast 文件配置该广播

public static class MyReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
            if (bo > 0) {
                if (bo > 240) {//刷票
                    handler.sendEmptyMessage(3);//弹窗警告 刷票
                } else {
                    handler.sendEmptyMessage(2);
                }
           }

        }
    }

在OnDestroy()中取消闹钟

 @Override
protected void onDestroy() {
    alarmManager.cancel(pendingIntent);
}

2.开启Thread

睡5s中去定时操作任务。

class MyRunnable  implements Runnable{

        @Override
        public void run() {
            while (isLoop){
                try {

                    if (bo > 0) {
                        if (bo > 240) {//刷票
                            handler.sendEmptyMessage(3);//弹窗警告 刷票
                        } else {
                            handler.sendEmptyMessage(2);
                        }
                    }
                    Thread.sleep(5000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

在onCreate()方法中开启:

loopThread=new Thread(new MyRunnable());
loopThread.start();

在页面销毁时终止掉该Thread

isLoop=false;
loopThread.interrupt();

3. 使用timer类。

开启timer

 Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
            //TODO ...

            }
        },new Date(),5000);

终止timer

  timer.cancel();

以上三种定时任务除了第一种不要随便使用外,推荐使用第三种和第二种。

csdn博客

我的微信公众号:行走的那些事,欢迎大家扫一扫。


行走的那些事
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,132评论 25 708
  • Android Studio JNI流程首先在java代码声明本地方法 用到native关键字 本地方法不用去实现...
    MigrationUK阅读 11,948评论 7 123
  • 如题,这一个月来都陷入上面的问题中,不知道自己为何考研,也不知道考上研究生我会开心吗? 总以为自己会找不到工作,阴...
    章橆鲔阅读 292评论 0 2
  • 一份满意的工作,一定是要有这3大因素的:自主、胜任、归属。 这些都是职场中稀缺的特质,要想找到一份这样的工作,也必...
    第二颗心脏阅读 364评论 0 2
  • (1月31日-2月9日,旅行11天。) “当我们看到雪花翩然飘下,看到太阳从山后缓缓升起,看到一束光神秘缥缈地射进...
    文心匠阅读 1,286评论 14 10