Android:网络操作2.3等低版本正常,4.0(ICS)以上出错,换用AsyncTask异步线程get json

问题:Android 低版本网络操作正常,4.0(ICS)以上出错

原因:4.0以上强制要求不能在主线程执行耗时的网络操作,网络操作需要使用Thead+Handler或AsyncTask

解决方案:网络操作改用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;

    }



}

NetworkTool.java

public class NetworkTool {

    public String getContentFromUrl(String url) {

        StringBuilder sb = new StringBuilder();

        try {

            InputStream is = new URL(url).openStream();

            InputStreamReader isr = new InputStreamReader(is, "utf-8");

            BufferedReader br = new BufferedReader(isr);

            String line = null;

            while ((line = br.readLine()) != null) {

                sb.append(line);

            }

            is.close();

        } catch (final IOException e) {

            return null;

        }

        return sb.toString();

    }

}

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");

taskSuccessful-成功,taskFailed-失败

你可能感兴趣的:(AsyncTask)