zoukankan      html  css  js  c++  java
  • 开启周期性的线程操作

    在开发过程中,碰到这么一种需求,需要在后台开启一个service服务,每隔一个小时请求一次网络数据,并更新桌面的widget组件。

    可行的方法有两种:

    1,借助于定时器。在service的oncreate方法中

    timer=new Timer();
            timer.schedule(new TimerTask(){
                @Override
                public void run() {
                    //因为service是在后台运行,并不存在ui阻塞的问题,因此可以不另开一个线程去请求网络信息                
                    place = getSharedPreferences("SP", Activity.MODE_PRIVATE)
                            .getString("name", "xcgy");
                    try {
                        new SendRequest().getLevelInfo(Constant.LevelInfoURL
                                + place, levelInfoSp, Constant.LevelKey);
                        // 发送广播通知appwidget进行更新
                        Intent intent = new Intent("wyf.action.aqi_upadte");
                        RefService.this.sendBroadcast(intent);
                        Thread.sleep(3600000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                }
                
            }, 0, 3600000);

    然后在service的ondistory方法中将定时器关闭。
    timer.cancle();

    2,借助线程休眠和标志位

    初始化的时候将flag设置为true。在service的oncreate方法中:

        while (flag) {
                    //因为service是在后台运行,并不存在ui阻塞的问题,因此可以不另开一个线程去请求网络信息                
                    place = getSharedPreferences("SP", Activity.MODE_PRIVATE)
                            .getString("name", "xcgy");
                    try {
                        new SendRequest().getLevelInfo(Constant.LevelInfoURL
                                + place, levelInfoSp, Constant.LevelKey);
                        // 发送广播通知appwidget进行更新
                        Intent intent = new Intent("wyf.action.aqi_upadte");
                        RefService.this.sendBroadcast(intent);
                        Thread.sleep(3600000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                }


    在service的ondistory方法中只需要将标志位设置为false即可。

  • 相关阅读:
    QProgressBar的使用例子
    kube框架结构-一个小型响应式CSS框架
    窗口类型(Widget, Window, Dialog, Desktop, SubWindow等等)
    Qt 之 设置窗口边框的圆角(使用QSS和PaintEvent两种方法)
    十大开源游戏引擎深入比较
    一种通用查询语言的定义与实践
    EF分页问题探讨之 OrderBy
    手把手教你做关键词匹配项目
    git
    Extension+NVelocity
  • 原文地址:https://www.cnblogs.com/bobodeboke/p/3010053.html
Copyright © 2011-2022 走看看