zoukankan      html  css  js  c++  java
  • 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:定义工具类,调用回调函数

    该工具类有以下属性:

    1. 类中有刚刚所定义的接口的对象
    2. 类的构造函数中,刚刚定义的接口作为參数
    3. 在须要调用接口函数的时候。调用接口函数

    我们在这里实现一个工具类,该工具类实现从网络中获取数据,当获取数据成功的时候,调用接口中的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()等这些函数事实上都是回调函数。

    事实上我们使用回调函数也能定义自己的下载工具类,等过几天我定义一个这种工具类,试验一下。大家能够试一下怎样自定义一个回调函数。

  • 相关阅读:
    [2011Summary Weekly]March.28April.1
    如何对需求分析人员进行考核测试角度
    算法实现三角形式输出C(n,k)
    Scrum 培训系列Scrum on a Page
    [练习]solveMaze
    excel中如何统计条件筛选后的条数
    开发人员绩效考核中"有效"bug数的统计
    Scrum 培训系列Scrum Lifecycle
    IIS6.0日志文件自定义类代码
    IIS6.0日志文件分析代码_3线程读取文件到数据库
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7289440.html
Copyright © 2011-2022 走看看