android回调函数

在咱们进行android开发的时候,经常遇到一些回调函数,当中,咱们最经常使用的回调就是,当咱们对一个组件设置监听的时候,事实上就相对于设置的回调函数。好比:php

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就是回调函数,这样看来,就至关于实现一个双向调用。java

咱们在进行android开发的时候。经常使用一些开源社区贡献的一些有关于网络获取数据或者是下载图片的开源包,这些包里面用到了很是多回调函数,现在咱们就是用一个获取网络数据的样例,来看一看怎样定义本身的回调函数。android

首先需要声明的是,回调函数是试用接口实现的。咱们一步一步来实现回调函数。apache

1:定义一个接口,当中定义一些需要用到的回调函数。markdown

名称:DownInterface.java网络

package interfaces;

public interface DownInterface {

    //需要用到的回调函数
    public void onDownloadSuccess(String result);
}

2:定义工具类,调用回调函数app

该工具类有如下属性:ide

  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()等这些函数事实上都是回调函数。

事实上咱们使用回调函数也能定义本身的下载工具类,等过几天我定义一个这种工具类,试验一下。你们可以试一下怎样自定义一个回调函数。

相关文章
相关标签/搜索