1、自定义异步Task
/** * 异步获取实时数据 */ public class TimerDataTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { String getUrl = mUrl + "/RealTimeData.ashx?type=data"; URL loginUrl = null; InputStream in = null; HttpURLConnection conn = null; //初始化列表 mDataList = new ArrayList<DataListItem>(); try { loginUrl = new URL(getUrl); conn = (HttpURLConnection) loginUrl.openConnection(); conn.setRequestProperty("Charset", "UTF-8"); if (conn.getResponseCode() == 200) { in = new BufferedInputStream(conn.getInputStream()); Scanner scanner = new Scanner(in).useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; Log.e(mLogTimerData,result); } conn.disconnect(); } catch (IOException ex){ Log.e(getString(R.string.log_e_url_error), ex.toString()); }catch (JSONException ex){ Log.e(getString(R.string.log_e_json_error), ex.toString()); } return true; } @Override protected void onPostExecute(final Boolean success) { // Message msg = new Message(); // uiHandler.sendMessage(msg); if(getActivity() != null) { getActivity().runOnUiThread(uiRefreshThread); } mTask=null; } @Override protected void onCancelled() { mTask=null; } }
2、在主线程刷新ListView
Runnable uiRefreshThread =new Runnable() { @Override public void run() { if(getActivity() != null) { //初始化Adapter mAdapter = new DataListAdapter(getActivity() , R.layout.fragment_data_list_item, mDataList); // Set the adapter mListView.setAdapter(mAdapter); mSwipeLayout.setRefreshing(false); mListView.setEnabled(true); } } };
Runnable uiThread = new Runnable(){ @Override public void run(){ mListView.setEnabled(false); } };
3、定时任务
Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if(getActivity() !=null) { getActivity().runOnUiThread(uiThread); mTask = new TimerDataTask(); mTask.execute((Void) null); } } };
每次刷新都是,重新new一个Adapter对象,使用notifyDataSetChanged(),会出现不定时BUG异常
时间: 2024-11-08 09:12:17