Android异步任务使用情况

时间:2013-04-06 20:09:04

标签: android asynchronous task

点击按钮,我想打开一个对话框。在那个对话框中,我想动态地设置文本(有点像秒表),文本将通过循环来实现。有人可以用示例代码指导我吗?我尝试了网上给出的很多例子,但却无法成功实现结果。

//Button where the action starts
public void onClickStart(View v) {
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setContentView(R.layout.activity_details);
    dialog.setTitle("Your Step Details");
    dialog.show();
    DisplayTask dd= new DisplayTask();
    dd.execute();
}

public void doWork(){
        final Handler handler=new Handler();
        new Thread(new Runnable (){
            boolean isRunning=true;
            @Override
            public void run() {
                while(isRunning){
                    try{
                        handler.post(new Runnable(){

                            @Override
                            public void run() {
                                try{
                                    TextView txtCurrentTime= (TextView)findViewById(R.id.txtLeft);
                                        Date dt = new Date();
                                        int hours = dt.getHours();
                                        int minutes = dt.getMinutes();
                                        int seconds = dt.getSeconds();
                                        String curTime = hours + ":" + minutes + ":" + seconds;
                                        txtCurrentTime.setText(curTime);
                                }catch (Exception e) {}

                            }

                        });
                    }catch(Exception e){

                    }
                }

            }

        }).start();
    }



public class DisplayTask extends AsyncTask<Void , Void, Void> {


    protected void onPostExecute(){
        MainActivity main= new Mai`enter code here`nActivity();
        main.doWork();
    }

    @Override
    protected Void doInBackground(Void... params) {
        onPostExecute();
        return null;
    }
}   

1 个答案:

答案 0 :(得分:0)

如果你想在计时器上做某事,AsyncTask不是正确的方法。使用Handler,并使用postMessageDelayed向其发布消息。这将允许您在几毫秒/秒内执行某些操作,但它将在UI线程上执行。