我有以下代码来执行PHP脚本:
public class CallPHPScript extends AsyncTask<ScriptNameAndParameters, Void, String> {
private Reply responder;
public interface Reply {
public void serverReply(String reply);
}
public CallPHPScript(Reply r) {
responder = r;
}
@Override
protected String doInBackground(ScriptNameAndParameters... arg) {
List<NameValuePair> params = arg[0].getParameters();
String scriptName = arg[0].getScriptName();
String json = MainActivity.makeCall(scriptName, params);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("SERVER REPLY", "Server Reply: " + result);
responder.serverReply(result);
}
}
public static String makeCall(String scriptName, List<NameValuePair> params) {
String address = SERVER_ADDRESS + scriptName + ".php";
Log.d("Main Activity", "Making call to server with: " + address);
HttpPost httpPost = new HttpPost(address);
HttpClient httpClient = new DefaultHttpClient();
StringBuilder total = new StringBuilder();
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line = "";
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
Log.d("CALLPHPSCRIPT", total.toString());
} catch (Exception e) {
e.printStackTrace();
}
return total.toString();
}
虽然它似乎工作正常,但我能看到的唯一输出是
// Return full string
Log.d("CALLPHPSCRIPT", total.toString())
这一行(以及我的回调)
Log.d("SERVER REPLY", "Server Reply: " + result);
永远不会被召唤。有没有人知道我哪里出错了?
答案 0 :(得分:1)
由于您解决了问题,因此违反了AsyncTask
的线程规则#3
这是正确使用课程的Threading rules
必须在UI线程上加载AsyncTask
类。这个完成了
自JELLY_BEAN
起。
必须在UI线程上创建任务实例。 必须在UI线程上调用execute(Params ...)。
请勿致电onPreExecute()
,onPostExecute(Result)
,
<{1}},doInBackground(Params...)
手动。
任务只能执行一次(如果是,则会抛出异常 尝试第二次执行。)
答案 1 :(得分:0)
刚才意识到我应该打电话给
CallPHPScript callPHP = new CallPHPScript(this);
callPHP.execute(new ScriptNameAndParameters("get_all_profiles",new ArrayList<NameValuePair>()));
而不是
CallPHPScript callPHP = new CallPHPScript(this);
callPHP.doInBackground(new ScriptNameAndParameters("get_all_profiles",new ArrayList<NameValuePair>()));
卫生署!
答案 2 :(得分:0)
(/)
记得优雅地关闭连接管理器和所有输入流
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
无需在
中拨打超级电话super.onPostExecute(result);