Activity的AsyncTask请求

工具类ActivityUtils代码:

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.util.concurrent.Callable;

public class ActivityUtils {

    private static ProgressDialog dialog;

    public static  void doAsync(final Context context, final String title, final String message,final Callable callable,final Callback callback){

        AsyncTask task=new AsyncTask() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if(context!=null && message!=null && !"".equals(message)){
                    dialog=ProgressDialog.show(context,title,message);
                }
            }

            @Override
            protected T doInBackground(Void... params) {
                try {
                    return callable.call();
                } catch (Exception e) {
                    e.printStackTrace();
                    if(dialog!=null){
                        dialog.dismiss();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(T result) {
                super.onPostExecute(result);
                if(dialog!=null){
                    dialog.dismiss();
                }
                callback.onCallback(result);
            }
        };

        task.execute();
    }
}

调用方式:

ActivityUtils.doAsync(mContext, "", "进行中...", new Callable() {

	@Override
	public String call() throws Exception {
		//将执行代码的返回值回调回去
		return Httpget.validproblem(jobno,time,scanStano,scanStationo,"11","22",createOperator);
	}
}, new Callback() {

	@Override
	public void onCallback(String myResult) {
		//结果处理
	}
});
回调接口函数:

public interface Callback {

    public void onCallback(final T result);
}




你可能感兴趣的:(Android)