Handlers vs Asynchronous calls in Android

余生颓废 提交于 2019-12-10 09:35:30

问题


Currently i am using Handlers to call web service methods to make it run in background. The problem is its taking more time to give the response, it seems to be more expensive in terms of performance. Now i plan to go for the Async Calls, which will be the best one? What are differences between Handlers and Async Calls in Android? Please help me to come up with a best solution.

For your reference I am giving some code snippets here

signIn.setBackgroundResource(R.drawable.signin_press);
changeImage=new Runnable(){
     public void run(){                                 
            signIn();
        }
    };      
signinHandler.post(changeImage);

When clicking the Sign in button i am calling this method, it looks like the UI is hanged for few minutes before calling the method. In this method, two expensive web services calls are involved to authenticate and register the user. How i can normalize the slowness of the app. Help me.


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/5300574/handlers-vs-asynchronous-calls-in-android

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