活动之间的缓慢转换 - AsyncTask无效

时间:2016-04-22 09:11:58

标签: android performance android-asynctask

我有2项活动,A& B.从A开始B会导致很长(2-4秒)的转换时间,因此我决定使用AsyncTask将重布局加载到viewFlipper中,该viewFlipper位于B的contentView中以释放UI线。换句话说,我想要实现的目标如下:

  
      
  1. 用户按下按钮,调用意图开始B. UI切换到B的contentView。
  2.   
  3. 在后台,AsyncTask正在一个名为“welcomeToContentView”的类中加载一个繁重的布局。
  4.   
  5. 完成后,布局将添加到B的viewFlipper。
  6.   

从A开始B:

Handler h = new Handler();
    h.postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(getBaseContext(), B.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
            intent.putExtras(b);
            startActivity(intent);
            A.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
        }
    }, 200);

在B中,在“onCreate()”期间将contentView设置为“content_view”:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
    }
    setContentView(R.layout.content_view);
    viewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
    new setWelcomeToLayoutTask(location, false).execute();
}

AsyncTask类如下:

private class setWelcomeToLayoutTask extends AsyncTask<Void, Void, Boolean> {
        private final MyLocation location;
        private final boolean animate;

    public setWelcomeToLayoutTask(MyLocation location, boolean animate) {
        this.location = location;
        this.animate= animate;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        Looper.prepare();
        if (welcomeToContentView == null) {
        // Heavy layout loading
            welcomeToContentView = (ViewLocationContentView.WelcomeToContentView)                        ViewLocationContentView.getContentView(B.this, "welcome_to");
            welcomeToContentView.setDescriptors(location);
            welcomeToContentView.setWelcomeToItems(location);                
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        ViewLocationActivity.this.addWelcomeToLayout(animate);
    }
}

private void addWelcomeToLayout(Boolean animate) {
    viewFlipper.addView(welcomeToContentView.getContentLayout(), animate);
}

现在,当按下应该导致B的contentView即时出现的按钮时,等待AsyncTask将布局​​加载到viewFlipper中,会发生什么情况是UI被卡在活动A中,并且只有所有布局都被加载到B的contentView中UI会发生变化。如何在按下按钮后立即将程序切换到B的contentView并在后台加载布局?

0 个答案:

没有答案