【发布时间】:2016-11-29 11:05:40
【问题描述】:
我尝试了几天来弄清楚,但没有成功,
目标:使用asyncTask通过IP获取使用国家,不卡住UI,并将其保存到字符串parm中。
问题: UI 在 asyncTask 完成工作之前不会移动:/
MainActivity ,onCreate 方法:
.......
JSONObject jsonObject;
try {
jsonObject = new getJSONObjectFromURL(LoginActivity.this).execute("http://ip-api.com/json").get();
if (jsonObject != null) {
if (!jsonObject.getString("status").equals("success"))
throw new InterruptedException();
Log.d(TAG, "onCreate: jsonObject.tostring:" + jsonObject.toString());
countryLocation = jsonObject.getString("country");
Log.d(TAG, "onCreate: countryByIP " + countryLocation);
}
if (!isNetworkAvailable()/* || countryLocation == null*/)
Toast.makeText(MainActivity.this, "Please enable data.", Toast.LENGTH_SHORT).show();
//in button click redo all that code for no internet connection,.
} catch (InterruptedException | ExecutionException | JSONException e) {
e.printStackTrace();
}
异步任务:
public class getJSONObjectFromURL extends AsyncTask<Object, Object, JSONObject> {
private Context context;
public getJSONObjectFromURL(Context context) {
this.context = context;
}
@Override
protected JSONObject doInBackground(Object... params) {
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL((String) params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String jsonString;
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
jsonString = sb.toString();
return new JSONObject(jsonString);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject result) {
//Update the String..
}
}
一切正常,我得到了 Json,能够从中读取 Country,但 MainActivity 等待 onPostExecute 继续。
【问题讨论】:
-
AsyncTask.get()... 那么您的期望是什么?
标签: java android json user-interface android-asynctask