Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何建模Android AsyncTask类?_Java_Android_Oop_Http_Asynchronous - Fatal编程技术网

Java 如何建模Android AsyncTask类?

Java 如何建模Android AsyncTask类?,java,android,oop,http,asynchronous,Java,Android,Oop,Http,Asynchronous,我决定学习Scala/Play(服务器端)并决定同时学习Android(客户端)游戏开发,以增加开发的乐趣。 我有一个关于如何在Android中为HTTP请求进行良好设计的问题。 据我所知,最好的方法是将HTTP请求委托给扩展抽象AsyncTask类的类。 您是否必须为覆盖的doInBackground方法中的每个不同逻辑执行AsyncTask的新扩展? 对我来说,每个请求逻辑都有一个类并不自然,而是将几个连贯的方法封装在一个类中 我刚开始玩一点,但我对设计不满意,因为我不喜欢我在doInBac

我决定学习Scala/Play(服务器端)并决定同时学习Android(客户端)游戏开发,以增加开发的乐趣。
我有一个关于如何在Android中为HTTP请求进行良好设计的问题。
据我所知,最好的方法是将HTTP请求委托给扩展抽象
AsyncTask
类的类。
您是否必须为覆盖的
doInBackground
方法中的每个不同逻辑执行
AsyncTask
的新扩展?
对我来说,每个请求逻辑都有一个类并不自然,而是将几个连贯的方法封装在一个类中

我刚开始玩一点,但我对设计不满意,因为我不喜欢我在
doInBackground(Object…params)
中设计的varargs对象
在这种设计中,我放松了类型安全性,params对象远远不够直观,这是我在代码中力求做到的

下面是我想要改进的代码

public class GameActivity extends Activity {

    private class MyCellListener implements ICellListener {
        public void onCellSelected() {
            ServerProxy.postSelectedCell(row, col, player.getUser());    
            ...
            // ServerProxy.other();

public class ServerProxy extends AsyncTask<Object, Void, Void>{

    private static final String TAG = ServerProxy.class.getSimpleName();
    private static final String SERVER_ADDRESS = "http://127.0.0.1";

    // Prevent external instantiation
    private ServerProxy(){};

    public static void postSelectedCell(int row, int cell, User user){
         List<NameValuePair> postParameters = new ArrayList<NameValuePair>(3);
         postParameters.add(new BasicNameValuePair("row", String.valueOf(row)));
         postParameters.add(new BasicNameValuePair("cell", String.valueOf(cell)));
         postParameters.add(new BasicNameValuePair("userName", user.getUserName()));
         new ServerProxy().doInBackground("setSelectedCell" , postParameters);
    }

//    public static void postOther() {
//      new ServerProxy().doInBackground("other" , //some parameters); 
//    }

    /**
     * @param postParameters First object URL postfix<br/>
     * Second parameter is post parameters inform of {@code List<NameValuePair>}
     * @return null
     */
    @SuppressWarnings("unchecked")
    @Override
    protected Void doInBackground(Object... params) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(SERVER_ADDRESS +"/" + params[0]);
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        try {
            httppost.setEntity(new UrlEncodedFormEntity((List<NameValuePair>) params[1]));
            httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
         Log.e(TAG,e.toString());
        } catch (IOException e) {
         Log.e(TAG,e.toString());
        }
        return null;
    }
}
公共类游戏活动扩展活动{
私有类MyCellListener实现了ICellListener{
公共void oncelselected(){
ServerProxy.postSelectedCell(行、列、player.getUser());
...
//ServerProxy.other();
公共类ServerProxy扩展异步任务{
私有静态最终字符串标记=ServerProxy.class.getSimpleName();
专用静态最终字符串服务器\u地址=”http://127.0.0.1";
//防止外部实例化
私有服务器代理(){};
公共静态void postSelectedCell(int行、int单元格、用户){
列表后参数=新的ArrayList(3);
添加(新的BasicNameValuePair(“行”,String.valueOf(行));
添加(新的BasicNameValuePair(“单元格”,String.valueOf(单元格));
添加(新的BasicNameValuePair(“userName”,user.getUserName());
新建ServerProxy().doInBackground(“setSelectedCell”,后参数);
}
//公共静态void postOther(){
//new ServerProxy().doInBackground(“其他”//一些参数);
//    }
/**
*@param postParameters第一个对象URL后缀
*第二个参数是post参数通知{@code List} *@returnnull */ @抑制警告(“未选中”) @凌驾 受保护的Void doInBackground(对象…参数){ HttpClient HttpClient=新的DefaultHttpClient(); HttpPost HttpPost=新的HttpPost(服务器地址+“/”+参数[0]); httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE\u EXPECT\u CONTINUE,false); 试一试{ setEntity(新的UrlEncodedFormEntity((列表)参数[1]); httpclient.execute(httppost); }捕获(客户端协议例外e){ Log.e(标记,e.toString()); }捕获(IOE异常){ Log.e(标记,e.toString()); } 返回null; } }
在设计之前,有些事情看起来你做错了

  • 您不应该像在这里那样直接调用
    doInBackground

    新建ServerProxy().doInBackground(“setSelectedCell”,后参数)

    相反,它应该调用任何

至于设计,你可以试试这个

  • 您可以创建一个
    ServerProxy
    类,而不是从
    AsyncTask
    扩展它。只需使用它封装逻辑即可
  • 现在您可以创建一个
    serverproxyanc
    ,它将
    ServerProxy
    作为组合
  • 现在你可以做的一个选择是

    公共类ServerProxy扩展异步任务

    这里的
    String
    可以是您想要在
    ServerProxy
    实例上调用的方法名,您可以使用反射来实现


注意:这个问题可能还有其他解决方法,这只是在设计之前第一次尝试解决这个问题,有些事情看起来你做错了

  • 您不应该像在这里那样直接调用
    doInBackground

    新建ServerProxy().doInBackground(“setSelectedCell”,后参数)

    相反,它应该调用任何

至于设计,你可以试试这个

  • 您可以创建一个
    ServerProxy
    类,而不是从
    AsyncTask
    扩展它。只需使用它封装逻辑即可
  • 现在您可以创建一个
    serverproxyanc
    ,它将
    ServerProxy
    作为组合
  • 现在你可以做的一个选择是

    公共类ServerProxy扩展异步任务

    这里的
    String
    可以是您想要在
    ServerProxy
    实例上调用的方法名,您可以使用反射来实现


注意:这个问题可能还有其他解决方法,这只是解决这个问题的第一次尝试。我想你不明白AsyncTask是做什么的。你不能在一个AsyncTask子类上定义像postLastName、postFirstName、postWhatever这样的方法,并让它在UI线程之外执行该方法。AsyncTask的目的是让它变得更简单执行需要更新UI的后台作业,而不强制您直接处理线程

为了与正在使用HttpClient的服务器通信,调用HttpClient.execute()将一直阻止,直到服务器的响应返回。这可能需要很长时间,特别是当服务器忙、死机或蜂窝无线电关闭时。当该调用花费太长时间时,您不希望UI停止响应用户。您希望显示旋转器旋转,以让用户知道发生了什么。如果使用了代码,则我认为您的UI将停止绘制,直到HttpClient.execute()调用返回,因为您正在UI线程上调用它

解决此问题的方法是将此调用从UI上移开
public class MyTask extends EnhancedAsyncTask<Param,Integer,MyResult> {
    MyParam1 param1;
    MyParam2 param2;

    public MyTask( MyParam1 param1, MyParam2 param2 ) {
        this.param1 = param;
        this.param2 = param2;
    }

    protected MyResult doInBackground( Param... params ) {
        // do server work here
        server.send( param1, param2 );
    }

    protected void success( MyResult result ) {
        // do Update of the UI
    }

    protected void handleException( Exception ex ) {
       // show an error here
    }
}

// Now to use this AsyncTask you would do something like this:

MyTask task = new MyTask( param1, param2 ).execute();