做项目时遇到一个问题,在跳转到一个新的活动时,oncreat中需要加载的东西过多,导致anr。于是想的是先进行initview的加载,然后让加载耗时的代码在线程中进行,完成之后再显示。
首先,建立线程池。
/** * 定义线程池,异步操作加载点 */ private int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); private int KEEP_ALIVE_TIME = 1; private TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS; private ExecutorService executorService = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES * 2, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, new LinkedBlockingDeque<Runnable>(128));
然后,建立handler和runnable;
private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { //若工作完成,取消动画,初始化界面 if (msg.what == 1) mProgressDialog.cancel(); /*//开始初始化界面 initView();*/ } }; /** * 线程 */ private Runnable mRunnable = new Runnable() { @Override public void run() { /* 需要耗时的工作 */ initData(); Message msg = mHandler.obtainMessage(); msg.what = 1; mHandler.sendMessage(msg); } };
接下来创建progressDialog;
/** * 创建ProrgressDialog */ private void createProgressDialog() { context = this; mProgressDialog = new ProgressDialog(context); mProgressDialog.setMessage("加载数据中,请稍等..."); //设置点击区域外的屏幕不关闭 mProgressDialog!!.setCanceledOnTouchOutside(false) mProgressDialog.show(); }
最后是在oncreat方法中调用。
//创建ProgressDialog createProgressDialog(); //启动线程 executorService.execute(mRunnable);