当我的服务运行 TimerTask 时,如何防止 UI 挂起?
我有一个包含 Timer 和 TimerTask 的服务,用于在一段时间内从 Web 服务接收数据。当我的 TimerTask 运行时,UI 会挂起,直到 Web 服务进程完成。如何将任务放入线程中以防止 UI 挂起?
我的代码:
Timer timerSyncFull = new Timer();
class taskSyncFull extends TimerTask {
@Override
public void run() {
hSyncFull.sendEmptyMessage(0);
}
};
final Handler hSyncFull = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
procSyncFull();
return false;
}
});
public void procSyncFull() {
try {
// My webservice process
} catch (Exception e) {
}
}
@Override
public void onStart(Intent intent, int startId) {
timerSyncFull = new Timer();
timerSyncFull.schedule(new taskSyncFull(), 5*60*1000,
5*60*1000);
}
I have a service which contains a Timer and TimerTask for receiving data from Webservice in periods of time. When my TimerTask runs, the UI hangs until the Webservice process complete. How can I put my task in a thread to prevent the UI hanging?
My code:
Timer timerSyncFull = new Timer();
class taskSyncFull extends TimerTask {
@Override
public void run() {
hSyncFull.sendEmptyMessage(0);
}
};
final Handler hSyncFull = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
procSyncFull();
return false;
}
});
public void procSyncFull() {
try {
// My webservice process
} catch (Exception e) {
}
}
@Override
public void onStart(Intent intent, int startId) {
timerSyncFull = new Timer();
timerSyncFull.schedule(new taskSyncFull(), 5*60*1000,
5*60*1000);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 AsyncTasks 或将您的 Handler 附加到另一个 Looper 线程。
Use AsyncTasks or attach your Handler to another Looper thread.
我使用了以下代码,我的问题得到了解决:
I used the following code and my problem solved:
只需在线程或 asyncTask 中调用 procSyncFull() 方法即可。
Simply invoke your procSyncFull() method in thread or asyncTask.
使用
AsyncTask
在doInBackground()
中执行并在onPostExecute()
中填充它AsyncTask 示例
use
AsyncTask
carry out your execution indoInBackground()
and populate it inonPostExecute()
AsyncTask Example