我需要定期从Android活动向服务器发送一个命令,然后接收输出并将其显示在活动的布局上。
我如何实现上述任务?
答案 0 :(得分:1)
我认为这是你正在寻找的那种东西:
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
}
根据您的需要进行更改。
答案 1 :(得分:-1)
在上述情况下,每次创建一个异步任务对象,但在这种情况下,不会多次创建对象,如果没有完成第一个请求,则将启动发送请求...
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);
};