【发布时间】:2012-01-07 22:40:34
【问题描述】:
我决定学习 Scala / Play(服务器端),并决定同时学习 Android(客户端)游戏开发,为开发增添趣味。
我有一个关于如何在 Android 中为 HTTP 请求做一个好的设计的问题。
据我了解,最好的方法是将 HTTP 请求委托给扩展抽象 AsyncTask 类的类。
您是否必须为您覆盖的 doInBackground 方法中的每个不同逻辑对 AsyncTask 进行新的扩展?
对我来说,为每个请求逻辑都有一个类并不自然,而是将几个连贯的方法封装在一个类中。
我刚开始玩一点,但我对设计不满意,因为我不喜欢doInBackground(Object... params) 中的可变参数对象的设计。
通过这种设计,我失去了类型安全性,并且 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;
}
}
【问题讨论】:
标签: java android oop http asynchronous