等到后台任务完成

时间:2012-09-14 13:32:45

标签: android multithreading view

我有一个活动类如下。

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会是一个选择。我对此不太清楚。

有什么想法吗?

2 个答案:

答案 0 :(得分: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
        }
    });

答案 1 :(得分:0)

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

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

并在AsyncTask中:

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

希望它会对你有所帮助。