Android callback function
During android development, we often encounter some callback functions. Among them, our most common callback is that when we set a listener for a component, in fact, it is relative to the set callback function. For example:
Button btn = (Button) findViewById (R. id. btn); btn. setOnClickListener (new Button. onClickListener () {// create listener public void onClick (View v) {String strTmp = click Button01; Ev1.setText (strTmp );}});
First, let's take a look at what is called a callback function. Assume that we have two classes: A and B. A needs to call the functions in B, but B also needs to call the C function in A. C is the callback function. In this case, it is equivalent to implementing a two-way call.
During android development, we often use some open-source community-contributed open-source packages for obtaining data from the network or downloading images. Many callback functions are used in these packages, now we use an example to get network data to see how to define our own callback function.
The first thing to declare is that the callback function is implemented through a trial interface. We will implement the callback function step by step.
1: Define an interface, which defines some callback functions that need to be used.
Name: DownInterface. java
Package interfaces; public interface DownInterface {// The required callback function public void onDownloadSuccess (String result );}
2: Define the tool class and call the callback function
This tool class has the following attributes:
In the constructor of the object class of the interface just defined in the class, the newly defined interface as a parameter calls the interface function when the interface function needs to be called.
Here we implement a tool class, which obtains data from the network. when the data is obtained successfully, we call the onDownloadSuccess () function in the interface to transmit the data to the object that calls the class.
The tool class is defined below:
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; // after the data processing is received, call the interface function 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;} // start to download 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); // obtain the response content 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); // enter the parameter in the POST Entity Log. e (url, StaticValue. URL + url); // get the response content HttpResponse response = new defaulthttpclient(cmd.exe cute (postMethod); // execute the POST method String back = EntityUtils. toString (response. getEntity (), UTF-8); Log. e (result, result = + back); // obtain the Response 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: use this tool class
Next, let's take A look at how to use this tool class. In Class A, assume there is A Button. Click this Button to get the data in the network. After the data in the network is obtained successfully, print the data.
Let's take a look at the called code:
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); }}
I see it. Are you familiar with it? We often use the download toolkit, which contains onLoading (), onSuccess (), onStop () and other functions, which are actually callback functions. In fact, we can use the callback function to define our own download tool class. In a few days, I will define such a tool class and try it out. You can try to define a callback function by yourself.