AsyncTask

作者: gaom明 | 来源:发表于2018-05-11 14:58 被阅读12次
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //region 刷新时间
    UpdateTime updateTime =  new UpdateTime();
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1) {
        updateTime.execute();
    } else {
        updateTime.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}

//region 刷新时间
public class UpdateTime extends AsyncTask<Integer, Integer, String> {
//后面尖括号内分别是参数(例子里是线程休息时间),进度(publishProgress用到),返回值 类型
@Override
protected void onPreExecute() {
//第一个执行方法
super.onPreExecute();
}

    @Override
    protected String doInBackground(Integer... params) {
        //第二个执行方法,onPreExecute()执行完后执行
        while(true)
        {
            publishProgress();
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onProgressUpdate(Integer... progress) {
        //这个函数在doInBackground调用publishProgress时触发,虽然调用时只有一个参数
        //但是这里取到的是一个数组,所以要用progesss[0]来取值
        //第n个参数就用progress[n]来取值
        Date dt=new Date();//如果不需要格式,可直接用dt,dt就是当前系统时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置显示格式
        String nowTime="";
        nowTime= df.format(dt);//用DateFormat的format()方法在dt中获取并以yyyy/MM/dd HH:mm:ss格式显示
        时间.setText(nowTime);

        String str = 时间.getText() + "";
        if (str.equals("2017-03-25 10:10:10")){
            int abc=0;
        }
        super.onProgressUpdate(progress);
    }

    @Override
    protected void onPostExecute(String result) {
        //doInBackground返回时触发,换句话说,就是doInBackground执行完后触发
        //这里的result就是上面doInBackground执行后的返回值,所以这里是"执行完毕"
        super.onPostExecute(result);
    }

}

相关文章

网友评论

      本文标题:AsyncTask

      本文链接:https://www.haomeiwen.com/subject/eimfdftx.html