Android使用AsyncTask异步线程网络通信获取数据(get json)

摘要:

  android 4.0以上强制要求不能在主线程执行耗时的网络操作,网络操作需要使用Thead+Handler或AsyncTask,本文将介绍AsyncTask的使用方法。

内容:

1.添加HttpTask.java

public class HttpTask extends AsyncTask<String, Integer, String> {
    private static final String TAG = "HTTP_TASK";

    @Override
    protected String doInBackground(String... params) {
        // Performed on Background Thread
        String url = params[0];
        try {
            String json = new NetworkTool().getContentFromUrl(url);
            return json;
        } catch (Exception e) {
            // TODO handle different exception cases
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String json) {
        // Done on UI Thread
        if (json != null && json != "") {
            Log.d(TAG, "taskSuccessful");
            int i1 = json.indexOf("["), i2 = json.indexOf("{"), i = i1 > -1
                    && i1 < i2 ? i1 : i2;
            if (i > -1) {
                json = json.substring(i);
                taskHandler.taskSuccessful(json);
            } else {
                Log.d(TAG, "taskFailed");
                taskHandler.taskFailed();
            }
        } else {
            Log.d(TAG, "taskFailed");
            taskHandler.taskFailed();
        }
    }

    public static interface HttpTaskHandler {
        void taskSuccessful(String json);

        void taskFailed();
    }

    HttpTaskHandler taskHandler;

    public void setTaskHandler(HttpTaskHandler taskHandler) {
        this.taskHandler = taskHandler;
    }

}

 

2.调用使用:

HttpTask task = new HttpTask();
task.setTaskHandler(new HttpTaskHandler(){
    public void taskSuccessful(String json) {
       try {
            JSONObject jsonObj = new JSONObject(json);
            String demo = jsonObj.getString("demo");
    } catch (Exception e) {
            e.printStackTrace();
       }
    }

    public void taskFailed() {
    }
});
task.execute("http://www.yourdomain.com/api/getjson");

 

原文:

王懿璞.Android:网络操作2.3等低版本正常,4.0(ICS)以上出错,换用AsyncTask异步线程get json[2014-07-14](2013-03-19).http://www.cnblogs.com/yipu/archive/2013/03/19/2969941.html

 

 

 

posted @ 2014-07-14 20:13  长城的草  阅读(9172)  评论(0编辑  收藏  举报