我试图在处理程序中重复调用asynctask并更新适配器,但它会挂起UI。现在我很困惑所以请告诉我如何重复调用asynctask和upd UI.I已确保asynctask只调用一次,直到它没有得到flagAsync的帮助完成。 处理程序代码如下。
private void RefreshData() {
mHandler = new Handler(Looper.getMainLooper());
// Create runnable for posting
mUpdateResults = new Runnable() {
public void run() {
InsideHandler();
}
};
int delay = 500;
int period = 500;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
在Handler中调用Asynctask - 代码在 -
之下 private void InsideHandler() {
if(aController.isNetworkAvailable() && flagAsync == 0)
{
flagAsync =1;
adapter.setNotifyOnChange(false);
MsgList.clear();
MsgList.addAll(db.getMsgList(teacherId));
adapter.notifyDataSetChanged();
PostMsgData(strUrl, strJson);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
postDataAsyn.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
postDataAsyn.execute();
}
}
private void PostMsgData(final String strUrl, final String strJson) {
postDataAsyn = new AsyncTask<String, String, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(strUrl).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
byte[] outputBytes = strJson.getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
int responseCode = httpcon.getResponseCode();
if(responseCode == 200)
{
InputStream inputStream = new BufferedInputStream(httpcon.getInputStream());
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return "ERROR";
}
@Override
protected void onCancelled()
{
super.onCancelled();
}
protected void onPostExecute(String result) {
}
}
答案 0 :(得分:0)
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
InsideHandler();
}
});
}
};
你能试试吗
答案 1 :(得分:0)
此链接可以帮助您解决问题。建议你使用runonthreadui来处理负载。
http://www.codota.com/android/methods/android.app.Activity/runOnUiThread
不要从处理程序调用asyntask。
答案 2 :(得分:0)
使用Haroon提供的代码并让计时器退出。使用runnable作为计时器这将解决你的问题(我希望哈哈:))