使用Timer从android做http请求

时间:2011-08-12 19:23:29

标签: android multithreading

我想写android聊天应用程序,我想知道 向Web服务器执行定期请求是一种好习惯 通过在

中打开新的AsynkTask线程使用Android Timer的新消息
private Runnable Timer_Tick = new Runnable() {
    public void run() {

    //This method runs in the same thread as the UI.               

    //Do something to the UI thread here

    }
};

方法?

感谢。

2 个答案:

答案 0 :(得分:1)

为什么不,但如果您希望聊天应用程序能够在屏幕关闭时向用户发送新消息通知,那么您可以在服务中实现计时器,也许更多是通过警报设置定期请求到服务器:

  • 设置闹钟(不精确重复)以向广播接收器发送意图。
  • 广播接收器启动服务。
  • service启动AsyncTask以请求Web服务器。
  • 如果有任何新消息,服务会向用户发送(或不发送)通知。
  • 服务自行停止。

答案 1 :(得分:0)

好的风格是你使用AlarmManager而不是简单的Timer。在AlarmManager任务中,您应该启动服务以执行同步操作(在简单的情况下,您可以使用IntentService)。操作完成后,服务会将新的同步任务发布到AlarmManager。