【发布时间】:2013-09-18 17:36:48
【问题描述】:
我有一个小型 Android 应用程序,我需要每隔几秒钟在其中执行一些 FTP 操作。 在了解了在 UI 线程上运行网络内容是 Android 不喜欢的艰难方式之后,我来到了这个解决方案:
// This class gets declared inside my Activity
private class CheckFtpTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... dummy) {
Thread.currentThread().setName("CheckFtpTask");
// Here I'll do the FTP stuff
ftpStuff();
return null;
}
}
// Member variables inside my activity
private Handler checkFtpHandler;
private Runnable checkFtpRunnable;
// I set up the task later in some of my Activitiy's method:
checkFtpHandler = new Handler();
checkFtpRunnable = new Runnable() {
@Override
public void run() {
new CheckFtpTask().execute((Void[])null);
checkFtpHandler.postDelayed(checkFtpRunnable, 5000);
}
};
checkFtpRunnable.run();
执行不能直接在 UI 线程上运行的重复性任务是一种好习惯吗? 此外,不是总是通过调用来创建新的 AsyncTask 对象
new CheckFtpTask().execute((Void[])null);
是否可以选择创建一次CheckFtpTask 对象然后重用它?
或者这会给我带来副作用吗?
提前致谢, 延斯。
【问题讨论】:
标签: android multithreading android-asynctask android-networking