如何在常规时间间隔内调用AsyncTask方法



我需要定期从android活动向服务器发送一个命令,然后接收输出并将其显示在活动的布局上。

我如何才能完成上述任务?

我想这就是你想要的东西:

public void myAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {       
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {       
                    try {
                        BackgroundTask backgroundTask = new BackgroundTask();
                        // The above is the class that performs your task
                        backgroundTask.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 50000); //this runs every 5 seconds. Feel free to change it
}

根据您的需要进行更改。

在上述情况下,每次都会创建一个异步任务对象,但在这种情况下,对象不会多次创建,并且在未完成第一个请求的情况下,将启动发送请求。。。

private void startFectchingTheData() {
    asynT.execute();
}
Runnable rannable = new Runnable() {
    @Override
    public void run() {
        asynT.execute();
    }
};
Handler handler = new Handler();
AsyncTask<Void, Void, Void> asynT = new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        // Write the fetching logic here
        return null;
    }
    protected void onPostExecute(Void result) {
        int interval = 5000;
        handler.postDelayed(rannable, interval);
    };
};
protected void onDestroy() {
    handler.removeCallbacks(rannable);
};

最新更新