json s数据能传给异步任务吗 android
发布网友
发布时间:2022-04-22 23:41
我来回答
共2个回答
热心网友
时间:2022-07-13 00:52
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");
热心网友
时间:2022-07-13 00:53
具体要做啥,不明白呀