Android: 네트워크 동작 2.3 등 저 버 전 정상, 4.0 (ICS) 이상 오류, AsyncTask 비동기 스 레 드 get json 으로 변경
7969 단어 AsyncTask
원인: 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 - 실패