【问题标题】:Run code in AsyncTask stucking UI在 AsyncTask 卡住 UI 中运行代码
【发布时间】: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


【解决方案1】:

您正在以同步状态运行您的AsyncTask

jsonObject = new getJSONObjectFromURL(LoginActivity.this).execute("http://ip-api.com/json").get();

通过调用get(),您正在等待Task 完成它的工作。如果您想要一个真正的异步进程,请不要使用get()。您可以使用回调来获得通知。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多