我決定學習Scala/Play(服務器端),並決定學習Android(客戶端)遊戲開發,同時爲之加油開發。
我有一個關於如何在Android中爲HTTP請求做一個很好的設計的問題。
從我所瞭解的最佳方法是將HTTP請求委託給擴展抽象AsyncTask
類的類。
您是否需要爲doInBackground
方法中的每個不同邏輯在AsyncTask
上重新進行擴展?
對我來說,每個請求邏輯都有一個類並不是很自然,而是在一個類中封裝了幾個相關的方法。如何建模Android 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;
}
}
我很感謝你的回答,但我認爲你錯誤地解釋了我的代碼/問題,或者我對自己的描述不好。你寫我如果我做兩次往返,我需要兩個實例。我會這樣做,因爲我所有的公共方法調用都使用新的ServerProxy()實例化一個新實例。如果我錯了,請糾正我,因爲你的代碼看起來不錯,但它根本不能解決我的問題?問題是在一個類中有許多不同類型的請求。例如一個Server類,以某種方式擴展AsyncTask,包含許多方法postFirstName,postLastName,getAllFriends等全部具有唯一參數。 – Farmor 2012-01-07 23:32:13
我更新了我的答案,以更好地解釋AyncTask實際上做了什麼,因爲我不認爲你瞭解它的目的。 – chubbsondubs 2012-01-08 03:36:07