android回调函数
在我们进行android开发的时候,经常遇到一些回调函数,其中,我们最常用的回调就是,当我们对一个组件设置监听的时候,其实就相对于设置的回调函数。例如:
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new Button.OnClickListener(){//创建监听    
            public void onClick(View v) {    
                String strTmp = "点击Button01";    
                Ev1.setText(strTmp);    
            }    
        }); 
首先我们了解一下什么叫做回调函数。假设我们有两个类,分别为A和B,其中A需要调用B中的函数,但是B也需要调用A中的函数C,则C就是回调函数,这样看来,就相当于实现一个双向调用。
我们在进行android开发的时候,经常使用一些开源社区贡献的一些有关于网络获取数据或者是下载图片的开源包,这些包里面用到了很多回调函数,现在我们就是用一个获取网络数据的例子,来看一看如何定义自己的回调函数。
首先需要声明的是,回调函数是试用接口实现的。我们一步一步来实现回调函数。
1:定义一个接口,其中定义一些需要用到的回调函数。
名称:DownInterface.java
package interfaces;
public interface DownInterface {
    //需要用到的回调函数
    public void onDownloadSuccess(String result);
}
2:定义工具类,调用回调函数
该工具类有以下属性:
- 类中有刚刚所定义的接口的对象
- 类的构造函数中,刚刚定义的接口作为参数
- 在需要调用接口函数的时候,调用接口函数
我们在这里实现一个工具类,该工具类实现从网络中获取数据,当获取数据成功的时候,调用接口中的onDownloadSuccess()函数,将数据传送给调用该类的对象。
下面我们定义这个工具类:
DownLoadEventNotifier .java
package interfaces;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.sdu.utils.StaticValue;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class DownLoadEventNotifier {
    private DownInterface dif;
    //处理数据接收完成之后,调用接口函数
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if(msg.what == 0){
                String back = (String)msg.obj;
                dif.onDownloadSuccess(back);
            }
        }
    };
    public DownLoadEventNotifier(DownInterface dif){
        this.dif = dif;
    }
    //开始进行下载
    public void start(String req,String url){
        new Thread(new DealThread(req, url)).start();
    }
    class DealThread implements Runnable{
        private String req;
        private String url;
        public DealThread(String req,String url){
            this.req = req;
            this.url = url;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            deal();
        }
        private void deal(){
            Log.e("req",req); //获取响应内容
            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();  
            params.add(new BasicNameValuePair("REQUEST", req));
            try {
                //http://jiduoduo.duapp.com
                //http://211.87.227.124/study.php
                HttpPost postMethod = new HttpPost(StaticValue.URL+url);
                postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
                Log.e("url",StaticValue.URL+url); //获取响应内容
                HttpResponse response = new DefaultHttpClient().execute(postMethod); //执行POST方法
                String back = EntityUtils.toString(response.getEntity(), "utf-8");
                Log.e("result", "result = " + back); //获取响应内容
                Message msg = Message.obtain();
                msg.obj = back;
                msg.what = 0;
                handler.sendMessage(msg);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
3:使用该工具类
下面我们看一下,如何使用该工具类,在A类中,假设有一个Button,点击该按钮之后,获取网络中的数据,当网络中的数据获取成功之后,打印出该数据。
下面我们看一下调用的代码:
package com.sdu.activities;
import interfaces.DownInterface;
import interfaces.DownLoadEventNotifier;
import com.sdu.androidmarket.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class TestActivity extends Activity{
    private Button btn;
    private DownLoadEventNotifier den;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                den = new DownLoadEventNotifier(new DownInterface() {
                    @Override
                    public void onDownloadSuccess(String result) {
                        // TODO Auto-generated method stub
                        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        super.onCreate(savedInstanceState);
    }
}
看到了吧,是不是感觉很熟悉?我们经常使用的下载工具包,里面有onLoading(),onSuccess(),onStop()等这些函数其实都是回调函数。其实我们使用回调函数也能定义自己的下载工具类,等过几天我定义一个这样的工具类,试验一下。大家可以试一下如何自己定义一个回调函数。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号