anroid 学习之java回调机制与自定义接口回调方法的使用

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的事件回调机制和匿名内部类的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值