我正在开发一个Android应用程序,我是线程的新手,如果我的问题很愚蠢我道歉,我使用 AsyncTask的doInBackground 方法将Stream转换为String然后在 onPostExecute 方法,应用程序将生成JSON对象。
我在模拟器(API 17)中启动了我的应用程序,它启动了完美但是当我在我的智能手机(galaxy s5)上启动它时,它花了太长时间,可能是10或15秒。 我认为doInBackground方法导致了这个问题。
这是我的主要类并在此处完成所有操作:
这是我调用我的Asynctask类并使用POST方法发送参数的地方:
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("register_number", phoneNumber.getText().toString()));
Log.i("LOG", "params hastttttttttt" + params.toString());
//
// Commands.readRegisterNumber(params);
// new readData().execute(params);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new readData().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
new readData().execute(params);
}
我在这里定义了 Asynctask 类:
private class readData extends AsyncTask<List<? extends NameValuePair>, Void, String>
Asynctask 类的doInBackground 方法:
@Override
protected String doInBackground(List<? extends NameValuePair>... params) {
List<? extends NameValuePair> param = params[0];
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("http://192.168.10.110:2233/api/register");
method.setEntity(new UrlEncodedFormEntity(param));
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return result;
}
这里是 onPostExecute 方法:
@Override
protected void onPostExecute(String result) { //doInBackground khorujish ro mide be in
if (result != null) {
try {
G.registerNumber.clear();
JSONObject object = new JSONObject(result);
StructRegisterNumber structRegisterNumber = new StructRegisterNumber();
structRegisterNumber.status = object.optString("status");
structRegisterNumber.code = object.optString("code");
structRegisterNumber.message = object.optString("message");
G.registerNumber.add(structRegisterNumber);
StructRegisterNumber registerNumber = G.registerNumber.get(0);
if (registerNumber.status != null && registerNumber.code != null) {
if (Integer.parseInt(registerNumber.status) == -1) {
Intent intent = new Intent(ActivityRegisterNumber.this, ActivityRegisterCode.class);
ActivityRegisterNumber.this.startActivity(intent);
}
}
progressDialog.dismiss();
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
progressDialog.dismiss();
}
}
答案 0 :(得分:0)
有很多原因可能导致它在真实设备上变慢:
答案 1 :(得分:0)
这并不是解决您的问题,但由于您只是在AsyncTask中从网络加载数据,因此您应该考虑使用诸如Volley之类的网络库,这样可以更轻松地实现。他们甚至支持Gson,它可以自动将返回的Json自动解析为对象。
文档: https://developer.android.com/training/volley/index.html
图书馆本身: https://android.googlesource.com/platform/frameworks/volley