我目前正在创建一个严重依赖AsyncTask的电子邮件应用程序。
在应用程序中,有五个选项卡,每个选项卡中都有一个片段(收件箱,发件箱,已发送,已保存)
当每个选项卡/片段打开数据库连接时,已合并一个加载微调器。此微调器在onPreExecute中启动,但将保持旋转,直到调用onPostExecute。但是,在某些情况下,没有调用onPostExecute,也没有调用doInbackground。
在做了一些研究后,我认为doInBackground可能没有执行,因为已经达到了线程限制/并发AsyncTask函数的数量。
因此,如何解决此问题以使doInbackground始终被执行?
Mainactive-创建一些片段:
private void createInboxFragment() { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); Fragment mailFragment = new InboxFragment(); transaction.add(R.id.layout_main, mailFragment, "Inbox"); transaction.commit(); } private void createOutboxFragment() { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); Fragment mailFragment = new OutboxFragment(); transaction.add(R.id.layout_main, mailFragment, "Outbox"); transaction.hide(mailFragment); transaction.commit(); } private void createSentFragment() { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); Fragment mailFragment = new SentFragment(); transaction.add(R.id.layout_main, mailFragment, "Sent"); transaction.hide(mailFragment); transaction.commit(); }
收件箱片段-AsyncTask
private class SetupUI extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { Log.d(TAG, "onPreExecute"); progressOverlay.setVisibility(View.VISIBLE); } @Override protected Boolean doInBackground(Void... params) { Log.d(TAG, "doInBackground"); try { // Start: SetupUI setSharedObjects(); setupLists(); getUnreadCount(); setupNotification(); createSharedRunnable(); initDBFunctions(); setupListView(); setupListViewCAB(); setupListViewClick(); // End: SetupUI } catch (Exception ex) { ACRA.getErrorReporter().handleSilentException(ex); ex.printStackTrace(); handleError(); } return true; } @Override protected void onPostExecute(Boolean result) { Log.d(TAG, "0 - onPostExecute"); AndroidUtils.animateView(progressOverlay, View.GONE, 0, 250); Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { Log.d(TAG, "1 - onPostExecute"); finaliseListView(); } }; handler.postDelayed(runnable, 750); } }
异步任务可以并行运行,但这取决于线程池的大小。android 3.0之前线程池大小为1。要同时运行,您可以调用
async task . executeonexecutor(async task。THREAD_POOL_EXECUTOR,null);
有关更多详细信息,请访问https://developer . Android . com/reference/Android/OS/async task . html # execute(Params...)