Android动画仅在AsyncTask完成后启动

Mat*_*and 1 android android-animation android-asynctask

我正在尝试创建一个本机登录屏幕,其中用户名和密码框在处理请求时滑出屏幕(如果登录失败则向上滑动).

为了实现这一点,我已经定义了我的animation(DropDownAnimation)并将其分配给我的LinearLayout(页脚).当用户单击"登录"按钮时,我启动动画,然后调用一个函数(tryLogin())启动AsyncTask.该AsyncTask手柄创建和发送的登录请求,并获得了所有的工作JSONObject响应.

但是,我的问题是slideDown动画直到AsyncTask完成后才开始.成功登录时看起来并不是那么糟糕,但是登录失败意味着LinearLayout从不向下滑动 - 它会跳到屏幕底部,开始slideUp动画回到原来的位置.

对于这个问题,这似乎是一个类似的问题,但我没有使用bindService(),我的所有非UI代码似乎(对我来说)AsyncTask已经包含在内.LogCat告诉我:

06-24 04:37:35.141: I/Choreographer(5347): Skipped 137 frames! The application may be doing too much work on its main thread.

我假设这些是页脚向下滑动的框架 - 但我无法弄清楚我在主线程上执行的是什么.这是我的LoginPage和LoginTask的代码.

LoginPage.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_page);

    login = (Button) findViewById(R.id.login);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    footer = (LinearLayout) findViewById(R.id.footer);

    // We must wait for the layout to be finalised before trying to find heights.
    ViewTreeObserver vto = footer.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            initAnimations();
        }
    });

    loading = (TextView) findViewById(R.id.loading);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String mUsername = username.getText().toString();
            String mPassword = password.getText().toString();

                            // Neither of these two things happen until after LoginTask is done.
            footer.startAnimation(slideDown);
            loading.setVisibility(TextView.VISIBLE);

            tryLogin(mUsername, mPassword);
        }
    });
}

protected void tryLogin(String mUsername, String mPassword) {
    Exception e;
    String loginUrl = getString(R.string.login_url);
    String clientId = getString(R.string.client_id);
    String clientSecret = getString(R.string.client_secret);
    LoginTask loginTask = (LoginTask) new LoginTask().execute(mUsername, mPassword, loginUrl, clientId, clientSecret);
    if ((e = loginTask.getException()) != null) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    } else {
        JSONObject response;
        try {
            response = loginTask.get();
            Log.d("login", response.toString());
            if (!response.has("access_token")) {
                loading.setVisibility(TextView.INVISIBLE);
                footer.startAnimation(slideUp);
                Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
            } else {
                Intent i = new Intent(this, FullscreenWebView.class);
                i.putExtra("accessToken", response.get("access_token").toString());
                startActivity(i);
                overridePendingTransition(0, 0);
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            Thread.currentThread().interrupt();
        } catch (ExecutionException e1) {
            e1.printStackTrace();
        } catch (JSONException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

LoginTask.java

class LoginTask extends AsyncTask<String, Void, JSONObject> {
    private Exception exception;

    @Override
    protected JSONObject doInBackground(String... params) {
        HttpURLConnection connection;
        OutputStreamWriter request = null;

        URL url = null;
        JSONObject response = null;
        String parameters = "grant_type=password&username="+params[0]+"&password="+params[1]+"&client_id="+params[3]+"&client_secret="+params[4];

        try {
            url = new URL(params[2]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();

            // username or password is probably wrong
            Log.d("login", ""+connection.getResponseCode());
            if (connection.getResponseCode() != 200) {
                return new JSONObject();
            }
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            Log.d("login", sb.toString());
            response = new JSONObject(sb.toString());

            isr.close();
            reader.close();
        } catch (Exception e) {
            this.exception = e;
        }

        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试成为LoginTask一个成员类LoginPage,并在onPreExecute()方法中启动动画,但这并没有改变任何东西.

任何帮助深表感谢!

ian*_*ake 5

使用时AsyncTask.get(),您正在阻止UI线程.当动画在UI线程上运行时,它看起来好像没有运行(实际上它被长时间运行的tryLogin方法阻止).

相反,您应该将依赖于结果的代码移动LoginTask到其onPostExecute方法:

protected void tryLogin(String mUsername, String mPassword) {
    String loginUrl = getString(R.string.login_url);
    String clientId = getString(R.string.client_id);
    String clientSecret = getString(R.string.client_secret);
    new LoginTask().execute(mUsername, mPassword, 
        loginUrl, clientId, clientSecret);
}
Run Code Online (Sandbox Code Playgroud)

LoginTask.java

class LoginTask extends AsyncTask<String, Void, JSONObject> {
    private Exception exception;

    @Override
    protected JSONObject doInBackground(String... params) {
        // Unchanged
    }

    public void onPostExecute(JSONObject response) {
        if (exception != null) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Log.d("login", response.toString());
            if (!response.has("access_token")) {
                loading.setVisibility(TextView.INVISIBLE);
                footer.startAnimation(slideUp);
                Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
            } else {
                Intent i = new Intent(this, FullscreenWebView.class);
                i.putExtra("accessToken", response.get("access_token").toString());
                startActivity(i);
                overridePendingTransition(0, 0);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)