前言:如果对android回调的概念不明白的请看:android 回调函数一:基本概念
1、定义接口
package com.app.util; public interface ZYJCallBack {
public void dataResult( String resultString ) ; public void progress( Integer progress ) ; public void start() ;
}
2、实体
package com.app.util;
import android.os.AsyncTask; public class ZYJAsyncTask extends AsyncTask< String , Integer , String > { ZYJCallBack zyjCallBack ; //开始
@Override
protected void onPreExecute() {
super.onPreExecute();
zyjCallBack.start();
} /**
* 特别注意:publishProgress( 10 );
* 这一句一定要写,否则 onProgressUpdate() ,这个方法不会被回调
*/
@Override
protected String doInBackground(String... params) {
publishProgress( );
publishProgress( );
publishProgress( );
publishProgress( );
return "哈哈哈,操作完成了" ;
} //onProgressUpdate方法用于更新进度信息
@Override
protected void onProgressUpdate(Integer... progresses) {
zyjCallBack.progress( progresses[] );
} @Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
zyjCallBack.dataResult( result );
} public void setCallBackListener(ZYJCallBack zyjCallBack){
this.zyjCallBack = zyjCallBack ;
}
}
3、回调
package com.android10;
import com.app.util.ZYJAsyncTask;
import com.app.util.ZYJCallBack; import android.app.Activity;
import android.os.Bundle; public class MainActivity extends Activity { @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main ); ZYJAsyncTask zyjAsyncTask = new ZYJAsyncTask() ;
zyjAsyncTask.setCallBackListener( new ZYJCallBack() { @Override
public void start() {
System.out.println("ssss开始了" ) ;
} @Override
public void progress(Integer progress) {
System.out.println("ssss进度为: " + progress ) ;
} @Override
public void dataResult(String resultString) {
System.out.println("ssss结果是:" + resultString ) ;
}
}); zyjAsyncTask.execute( "" ) ;
}
}
4、运行结果
ssss开始了
ssss进度为: 10
ssss进度为: 20
ssss进度为: 50
ssss进度为: 100
ssss结果是:哈哈哈,操作完成了