0

我有一个活动课程如下。

public class LoginActivity extends Activity implements OnClickListener {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      button1 = (ImageView) findViewById(R.id.button1);
      button1.setOnClickListener(this);
   }
   @Override
   public void onClick(View v) {
       BackgroundRunner bgRunner = new BackgroundRunner(this);
       String[] params = new String[]{url};
       bgRunner.execute(params);
   }


}

AsyncTask 是:

 public class BackgroundRunner extends AsyncTask<String, Void, Boolean>  {

@Override
protected Boolean doInBackground(String... params) {
    ServiceCaller serviceCaller = new ServiceCaller();
    boolean status = serviceCaller.checkLogin(params[0]);
    return status;
}

@Override
public void onPreExecute(){
    progressBar = (ProgressBar) currentContext.findViewById(R.id.loader);
    progressBar.setVisibility(View.VISIBLE);
     }

@Override
public void onPostExecute(final Boolean status){
    progressBar.setVisibility(View.INVISIBLE);
}

}

这是场景。主活动类在单击时创建一个线程。然后创建的线程从服务器获取一些数据。这是一项耗时的任务。因此,UI 上会显示一个进度条。目前我正在使用 AsyncTask 来完成服务器数据检索。但真正的挑战是等待后台任务完成并从中获取价值。我正在寻找的是:

等到服务器调用并获得结果。同时显示进度条。我认为 Handler 将是一个选择。我对此不太清楚。

有什么想法吗?

4

2 回答 2

2

我的解决方案是创建自己的 asynctask 类:

 import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import br.com.zcr.ezcrm.R;

public class AsyncTask implements Runnable {

    private Activity activity;
    private Handler handler;
    private Action action;
    private boolean showDialog = true;
    private boolean running = false;
    private boolean canceled = false;

    private Thread t;

    private ProgressDialog progress;

    public AsyncTask(Activity activity) {
        this.activity = activity;
        handler = new Handler();
    }

    public AsyncTask(Activity activity, Action action) {
        this.activity = activity;
        this.action = action;
        handler = new Handler();
    }

    private ProgressDialog getDialog() {
        if (progress != null)
            return progress;
        progress = ProgressDialog.show(activity, null, activity.getString(R.string.carregando), true, false);
        progress.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                setCanceled(true);
            }
        });
        return progress;
    }

    private void showDialog() {
        if (showDialog)
            getDialog().show();
    }

    private void hideDialog() {
        if (showDialog)
            getDialog().dismiss();
    }

    public void execute(boolean showDialog) {

        this.showDialog = showDialog;
        execute();
    }

    public void execute() {

        if (running || action == null)
            return;

        running = true;

        // Utils.setFixedOrientation(activity);
        showDialog();
        t = new Thread(AsyncTask.this);
        t.start();
    }

    @Override
    public void run() {

        try {

            final Object o = action.run();

            if (canceled)
                return;

            handler.post(new Runnable() {
                public void run() {
                    action.onFinnish(o);
                }
            });

        } catch (final Exception e) {

            if (canceled)
                return;

            handler.post(new Runnable() {
                public void run() {
                    action.onError(e);
                }
            });

        } finally {

            canceled = false;
            hideDialog();
            // Utils.setUnfixedOrientation(activity);
            running = false;
        }

    }

    /*
     * public void stop() { running = false; }
     */
    public void setAction(Action a) {
        action = a;
    }

    public void setCanceled(boolean canceled) {
        if (canceled)
            t = null;
        this.canceled = canceled;
    }

    public interface Action {
        /** Acao a ser executada */
        public Object run() throws Exception;

        /** Chamado no fim de todas as execucoes */
        public void onFinnish(Object result);

        /** Para qualquer execucao e retorna o erro */
        public void onError(Exception e);
    }

}

这是实现:

    AsyncTask task = new AsyncTask(this, new Action() {
        public Object run() throws Exception {
            return WebService.autenticate(login, pass);
        }
        public void onFinnish(Object result) {
//result was returned in run method
            verifyLogin((String) result);
        }
        public void onError(Exception e) {
            //error
        }
    });
于 2012-09-14T13:38:16.443 回答
0

在此代码之前显示进度对话框:

dialog.show()
bgRunner.execute(params);

在 AsyncTask 中:

onPostExecute((final Boolean status){
    dialog.cancel() // MAKE DIALOG CANCEL
}

希望它会帮助你。

于 2012-09-14T13:38:03.820 回答