Handlers vs Asynchronous calls in Android

别等时光非礼了梦想. 提交于 2019-12-05 18:03:36
Quintin Robinson

There are certain advantages to using Thread and Handler respectively to using AsyncTask it really depends on your usage and the profiling of those benefits vs detriments will likely come down to you.

I would recommend the article Painless Threading for a little understanding of threading on Android.

EDIT for additional info in question.

If we adapt the code from the Painless Threading article that was linked you can get something like so.

  new Thread(new Runnable() {
    public void run() {
      signIn();
      signinHandler.post(new Runnable() {
        public void run() {
          //TODO: Something to notify of login complete / continue processing.
        }
      });
    }
  }).start();

In the TODO you need to continue or notify execution, I don't know what is currently handled in signIn() so if that crosses the UI thread it will have to be refactored.

AsyncTask uses a thread pool and handlers internally. It's not magic; see the source. Performance won't be measurably better than your own handlers (except for the fact that using a thread pool may save a small bit of overhead for creating a new thread, but that's pretty negligible compared the the duration of typical web service calls; the extra few milliseconds certainly won't make a user-noticeable impact). Given the number of factors involved in making a web request, what would make you think the thread/handlers are what's slowing down your app (as opposed to your network connection, server traffic, etc.)? Does profiling your code back that assertion up?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!