AsyncTask Android - 设计模式和返回值 [英] AsyncTask Android - Design Pattern and Return Values

查看:19
本文介绍了AsyncTask Android - 设计模式和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序来验证外部网络服务器上的登录凭据 - 所以我有一个创建登录屏幕的基本问题,当提交时,它会在后台向服务器发送 HTTP 请求,而不会导致 UI 挂起- 同时向用户提供 ProgressDialog.

I'm writing an application that validates login credentials on an external webserver - so I have the basic issue of creating a login screen that when submitted will send an HTTP request to a server in the background and not cause the UI to hang - whilst providing a ProgressDialog to the user.

我的问题在于,我想编写一个扩展 AsyncTask 的通用 HTTP 请求类,因此当我调用 .execute() 时,我将传递可能包含post"之类的字符串参数,当 doInBackground 被调用时,这将看到post"字符串,然后将这些参数转发到我的类中的相应调用.伪代码类似于

My problem lies in, I want to write a generic HTTP Request class that extends AsyncTask, so when I call .execute() I will then pass String parameters which may contain something like 'post', and when doInBackground is called this will see the 'post' string and then forward those parameters onto the respective call in my class. Pseudo code would be something like

public class HTTPOperations extends AsyncTask<String, Void, String>
{
doInBackground(String... string1,additionalParams)
{
  if string1.equals "post"
      response = httpPost(additionalParams)
       return response;
}

httpPost(params)
{
// do http post request
}
}

这就是我能想到的,除了为我希望发出的每个 HTTP Post/GET 等请求创建一个类并扩展 ASyncTask...

This is all I could think of, other than creating a class for every HTTP Post/GET etc request I wish to make and extending ASyncTask...

这导致了我的下一个问题,如果 HTTP POST 成功并返回身份验证令牌,我如何访问此令牌?

Which leads me to my next problem, if the HTTP POST is successful and it returns an authentication token, how do I access this token?

因为新的httpOperations.execute(),不会从doInBackground返回字符串,而是返回一个

Because new httpOperations.execute(), does not return the string from doInBackground, but a value of type

对不起,如果这没有意义,我根本无法弄清楚.如果需要,请详细说明.AsyncTask 设计模式和想法非常受欢迎.

Sorry if this doesn't make sense, I can't figure this out at all. Please ask for elaboration if you need it. AsyncTask design patterns and ideas are hugely welcomed.

推荐答案

如果您正在为此类设计可重用的任务,则需要确定可重用的返回类型.它是您的设计决定.问问自己,我的 HTTP 操作在调用它们的机制和处理它们的数据的机制上是否相似?"如果是这样,您可以设计一个类来完成这两项工作.如果没有,您可能需要不同的类来进行不同的远程操作.

If you are designing a reusable task for something like this, you need to identify a reusable return type. Its a design decision on your part. Ask yourself, "Are my HTTP operations similar in both the mechanisms with which they are called and in which their data is processed?" If so, you can design a single class to do both. If not, you probably need different classes for your different remote operations.

在我个人使用中,我有一个附加键值对的对象,常见的返回类型是 HttpEntity.这是 HTTP Get 和 Post 的返回类型,这在我的场景中似乎可以正常工作,因为我在异常 HTTP 结果情况下抛出异常,例如 404.此设置的另一个不错的方面是将参数附加到 get 的代码或者 post 非常相似,所以这个逻辑很容易构建.

In my personal use, I have an object i attach key value pairs to and the common return type is the HttpEntity. This is the return type for both HTTP Get and Post, and this seems to work ok in my scenarios because i throw exceptions in exceptional HTTP result situations, like 404. Another nice aspect of this setup is that the code to attach parameters to a get or post are fairly similar, so this logic is pretty easy to construct.

一个例子是这样的(伪):

An example would be something like this (psuedo):

public interface DownloadCallback {
   void onSuccess(String downloadedString);
   void onFailure(Exception exception);
}

然后在你的代码中,你要去哪里下载:

Then in your code, where you go to do the download:

DownloadCallback dc = new DownloadCallback(){
   public void onSuccess(String downloadedString){
     Log.d("TEST", "Downloaded the string: "+ downloadedString);
   }
   public void onFailure(Exception e){
     Log.d("TEST", "Download had a serious failure: "+ e.getMessage());
   }
 }

 DownloadAsyncTask dlTask = new DownloadAsyncTask(dc);

然后在DownloadAsyncTask的构造函数中,存储DownloadCallback,当下载完成或失败时,调用与事件对应的下载回调上的方法.所以...

Then inside the constructor of DownloadAsyncTask, store the DownloadCallback and, when the download is complete or fails, call the method on the download callback that corresponds to the event. So...

public class DownloadAsyncTask extends AsyncTask <X, Y, Z>(){
  DownloadCallback dc = null;

  DownloadAsyncTask(DownloadCallback dc){
    this.dc = dc;
  }

  ... other stuff ...

  protected void onPostExecute(String string){
    dc.onSuccess(string);
  }
}

我要重申,我认为为了你自己的利益,你应该传回 HttpEntities.String 现在看起来是个好主意,但是当您想在 http 调用背后执行更复杂的逻辑时,它确实会导致麻烦.当然,这取决于你.希望这会有所帮助.

I'm going to reiterate that I think for the good of yourself, you should pass back HttpEntities. String may seem like a good idea now, but it really leads to trouble later when you want to do more sophisticated logic behind your http calls. Of course, thats up to you. Hopefully this helps.

这篇关于AsyncTask Android - 设计模式和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆