android中经常会用到内部类方式的监听接口,如按钮中的onClickListener等,内部类接口中会用到回调方法;同时在多线程操作中,子线程进行耗时操作时,如向服务器发送请求,服务器的数据响应是无法进行的,这时候需要利用java的回调机制解决问题。通过重写回调方法获取请求结果
这里以网络下载为例,封装一个网络下载类,并且实现自定义接口回调方法;
先建立一个接口:
package com.example.menu;
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
建立封装的网络操作工具类
package com.example.menu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.example.menu.HttpCallbackListener;
public class HttpUtil {
public static void sendHttpRequest(final String address,final HttpCallbackListener listner){
new Thread(new Runnable(){
public void run() {
HttpURLConnection connection=null;
try {
URL url =new URL(address);
connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in =connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuilder response= new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
if(listner!=null){
listner.onFinish(response.toString());
}
} catch (Exception e) {
if(listner!=null){
listner.onError(e);
}
}finally{
if(connection!=null){
connection.disconnect();
}
}
}
}
).start();
}
}
在mainActivity活动中使用工具类
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
final Handler handler =new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==1){
String info =(String) msg.obj;
Toast.makeText(getApplicationContext(), ""+info, Toast.LENGTH_SHORT).show();
}
}
};
HttpUtil.sendHttpRequest("http://www.baidu.com",new HttpCallbackListener(){
public void onFinish(String response) {
System.out.println(response);
Message msg =handler.obtainMessage();
msg.what=1;
msg.obj=response;
handler.sendMessage(msg);
};
public void onError(Exception e) {
System.out.println("系统出错:"+e.toString());
};
});
}
上面代码中通过HttpUtils工具类的sendHttpRequest()方法,传递一个网址参数,通过子线程操作执行数据下载,然后通过重写接口实例,重写接口方法,获取了之前操作的结果;然后将结果通过Handler发送消息,当handler触发handMessage回到方法的时候,就可以获取最终的效果!整个过程用到了接口回调机制和之前常用的监听器效果大同小异,非常有助于理解android的事件回调机制和匿名内部类的使用