android service异步网络加载怎么实现
发布网友
发布时间:2022-10-10 05:50
我来回答
共1个回答
热心网友
时间:2024-11-07 17:30
**
* 封装ProecssDialog对话框
*
*/
public class LoadDialog extends ProgressDialog {
private String title = "进度对话框";
private String message = "加载数据中....";
public LoadDialog(Context context, int theme) {
super(context, theme);
}
/**
* 用默认的标题和内容来创建对话框
* @param context
*/
public LoadDialog(Context context) {
super(context);
initDialog();
}
/**
* 用指定的标题和内容来创建对话框
* @param context
* @param title
* @param message
*/
public LoadDialog(Context context,String title,String message){
super(context);
if(title != null){
this.title = title;
}
if(message != null){
this.message = message;
}
initDialog();
}
/**
* 初始化对话框参数,默认对话框不可以取消
*/
public void initDialog(){
setTitle(title);
setMessage(message);
setProgressStyle(ProgressDialog.STYLE_SPINNER);
setCancelable(false);
}
/**
* 打开对话框,设置回调方法,传递需要执行业务方法的类模板,方法名和参数列表
* @param callback 回调方法,该方法在对话框关闭后回调,并获取返回的数据
* @param serviceClass 执行业务方法的类模板
* @param method 执行业务方法的方法名
* @param params 执行业务方法的参数列表
*/
public void execute(Callback callback,Class serviceClass,String method,Object... params){
super.show();
ServiceAysnTask task = new ServiceAysnTask(callback,serviceClass,method);
task.execute(params);
}
/**
* 回调方法的接口
*
*/
public interface Callback{
public void getResult(Map map);
}
/**
* 与远程服务通信的线程类
* @author BDK
* AsyncTask 异步任务
*/
private class ServiceAysnTask extends AsyncTask<object,object,map>{
private Class serviceClass;
private String method;
private Callback callback;
public ServiceAysnTask(Callback callback,Class serviceClass,String method){
this.callback = callback;
this.serviceClass = serviceClass;
this.method = method;
}
@Override
protected Map doInBackground(Object... params) {
Map resultMap = null;
try {
Object obj = serviceClass.newInstance();//创建类模板对象
Class [] paramTypes = new Class[params.length];
for (int i = 0; i < paramTypes.length; i++) {
paramTypes[i] = params[i].getClass();
}
//根据类模板得到方法
Method m = serviceClass.getMethod(method, paramTypes);
resultMap = (Map) m.invoke(obj, params);
} catch (Exception e) {
e.printStackTrace();
}
LoadDialog.this.cancel();
return resultMap;
}
@Override
protected void onPostExecute(Map result) {
super.onPostExecute(result);
if(result == null){
Toast.makeText(LoadDialog.this.getContext(), "网络通信异常", Toast.LENGTH_LONG).show();
return;
}
callback.getResult(result);
}
}
}
</object,object,map>