多语言展示
当前在线:1036今日阅读:26今日分享:39

ndroid回调函数定义

该经验主要是指导android开发新手进行回调函数的定义和应用.以此为基础创建更加复杂的回调函数.
工具/原料
1

eclipse

2

java

方法/步骤
1

在我们进行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开发的时候,经常使用一些开源社区贡献的一些有关于网络获取数据或者是下载图片的开源包,这些包里面用到了很多回调函数,现在我们就是用一个获取网络数据的例子,来看一看如何定义自己的回调函数。首先需要声明的是,回调函数是试用接口实现的。我们一步一步来实现回调函数。

2

1:定义一个接口,其中定义一些需要用到的回调函数。名称:DownInterface.javapackage interfaces;public interface DownInterface {    //需要用到的回调函数    public void onDownloadSuccess(String result); }

3

2:定义工具类,调用回调函数该工具类有以下属性:类中有刚刚所定义的接口的对象类的构造函数中,刚刚定义的接口作为参数在需要调用接口函数的时候,调用接口函数我们在这里实现一个工具类,该工具类实现从网络中获取数据,当获取数据成功的时候,调用接口中的onDownloadSuccess()函数,将数据传送给调用该类的对象。下面我们定义这个工具类:DownLoadEventNotifier .javapackage 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 params = new ArrayList();  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();            }        }    } }

4

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);    } }

注意事项

1:代码直接复制粘贴即可使用

推荐信息