3

我有AsyncTask一个班级。我希望它在执行时显示进度。但它不打印日志。

private void registerBackground() {
    new AsyncTask<Void, Integer, String>() {

        @Override
        protected String doInBackground(Void... params) {
            Log.v("TAGGG", "IN doInBackground");
            msg = "Error: ";

            return msg;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            Log.v("TAGGG", "Progress: " + progress[0] + "%");
        }

        @Override
        protected void onPostExecute(String msg)
        {
            Log.v("TAGGG", msg);
        }
    }.execute();
}
4

1 回答 1

9

您必须使用 publishProgress() 方法:http: //developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)

可以从 doInBackground(Params...) 调用此方法以在后台计算仍在运行时在 UI 线程上发布更新。每次调用此方法都会触发 UI 线程上 onProgressUpdate(Progress...) 的执行。如果任务被取消,onProgressUpdate(Progress...) 将被调用。

    @Override
    protected String doInBackground(Void... params) {
        Log.v("TAGGG", "IN doInBackground");
        msg = "Error: ";
        int i = 0;
        while (i <= 50) {
            try {
                Thread.sleep(50);
                publishProgress(i);
                i++;
            }
            catch (Exception e) {
                Log.i(TAGGG, e.getMessage());
            }
        }
        return msg;
    }
于 2013-07-27T05:58:59.057 回答