zoukankan      html  css  js  c++  java
  • Android创建定时和周期任务

    问题:应用需要按时执行某个操作,例如定时更新UI。

    解决方案:使用Handler提供的定时操作功能。通过Handler,可以在指定的时间或是指定的延时后执行操作。

    下面看一个在TextView中显示当前时间的Avtivity。

    import java.util.Calendar;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.app.Activity;
    import android.widget.TextView;
    
    public class TimingActivity extends Activity {
    
        private Handler mHandler = new Handler();
        private TextView mClock;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mClock = new TextView(this);
            setContentView(mClock);
        }
        
        private Runnable timerTask = new Runnable() {
            
            @Override
            public void run() {
                Calendar now = Calendar.getInstance();
                mClock.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR) 
                                                             ,now.get(Calendar.MINUTE) 
                                                             ,now.get(Calendar.SECOND)));
                //设置1秒之后再次更新
                mHandler.postDelayed(timerTask, 1000);
            }
        };
        
        //OnCreate执行后会执行onResume方法
        protected void onResume() {
            super.onResume();
            mHandler.post(timerTask);
        };
        
        @Override
        protected void onPause() {
            super.onPause();
            mHandler.removeCallbacks(timerTask);
        }
        
    }
  • 相关阅读:
    python入门-函数(二)
    python入门-函数(一)
    python入门-WHILE循环
    python入门-用户输入
    python入门-字典
    Spring Security授权 AccessDecisionManager
    Java的性能优化
    datahub
    vbs mytest
    spring发布和接收定制的事件(spring事件传播)
  • 原文地址:https://www.cnblogs.com/chenjianxiang/p/3863594.html
Copyright © 2011-2022 走看看