Callbacks in android - interface callbacks

It is found that many beginners do not have a thorough understanding of concepts such as callbacks, interfaces, and abstractions.

Today, I will explain the interface callback to everyone based on my experience. Suitable for beginners to see.

Let me briefly talk about my understanding first,  

The so-called interface callback.

You define the interface first, and then use it under certain conditions. Many beginners may be confused when they start, but in fact, this is something you use every day. For example, if you click a button, you will consciously set its listener (onclick event) to implement its onclick method.

1, when the user sends out this onclick event (the user clicks a button, etc.).

2. The system calls the listener you set (set onclickListener).

3, Produce different results according to your implementation (code implemented in onclick).

Next, let's take the example of obtaining json data from the network in android to explain in detail what the so-called interface callback is.

For android, we first understand a few concepts.

1. Android does not allow returning to the network in the main thread (Main thread), long-term I/O operations, and some time-consuming operations (this is well understood, it is to give users a friendly experience, so the UI cannot be blocked)

2. UI components cannot be operated in sub-threads (that is, operations such as textview imageview listview cannot be directly assigned to in sub-threads)

3, so we complete the above operations through thread communication (thread + handler or through AsyncTask to complete our operations)

I choose thread + header to complete this operation (AsyncTask is an operation that Google encapsulates thread + handler)

1. First of all, let’s define the interface first. Don’t ask why. If you ask, I will tell you that for general programming (or to encapsulate the changed things, it is to encapsulate the step of obtaining data from the network, but after obtaining the data There will be a variety of operations, so I can’t control how you operate, it is the so-called general programming, if you still understand it, then let’s do it first!)

To define the interface, we can think about which callbacks are needed.

a, one for successful access to the network and one for failure. These two are very necessary, and there are usually others (one is called at the beginning, and one can set the progress of access during loading)

Simply write an interface as follows:

/**
	 * 网络请求监听接口
	 * @author cyl
	 * email:[email protected]
	 * 2016年2月27日
	 */
	public interface CylNetListener{
		/**
		 * 开始加载
		 */
		public void start();
		/**
		 * 加载失败
		 * @param code  访问网络的状态码
		 * @param msg   错误异常信息
		 */
		public void onError(int code,String msg);
		/**
		 * 加载成功
		 * @param content
		 */
		public void onSuccess(String content);
	}

2. The following is the core implementation class  

package com.cyl.callbactest.network;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Handler;
import android.os.Message;
import com.cyl.callbactest.service.CylNetListener;
/**
 * 
 * @author cyl
 * @email [email protected]
 * 2016年3月21日
 */
public class CylNetWork {
	private CylNetListener listener;
	/**
	 * 开始访问
	 */
	public final static int startCode = 100;
	/**
	 * 错误
	 */
	public final static int onEorrorCode = 101;
	/**
	 * 得到数据
	 */
	public final static int onSuccessCode = 102;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			int what = msg.what;
			switch (what) {
			case startCode:
				if(listener != null){
					listener.start();
				}
				break;
			case onEorrorCode:
				if(listener != null){
					listener.onError(msg.arg1, (String)msg.obj);
				}
				break;
				
			case onSuccessCode:
				if(listener != null){
					if(listener != null){
						listener.onSuccess((String)msg.obj);
					}
				}
				break;
			default:
				break;
			}
		}
	};
	/**
	 * 网路访问
	 * @param url 要访问的地址
	 */
	public void request(final String url){
		//这里是简单写的 只对http  协议简单判断了一下 
		if(!url.contains("http")){
			Message msg = Message.obtain();
			msg.what = onEorrorCode;
			msg.arg1 = 404;
			msg.obj = "不是http协议";
			handler.sendMessage(msg);
			return;
		}
		//程序更好的  运行  这里  的线程通过线程池 进行管理
		new Thread(new Runnable() {
			@Override
			public void run() {
				int code = 404;
				try {
					handler.sendEmptyMessage(startCode);
					HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
					code = connection.getResponseCode();
					//可以connection 进行各种设置 超时  ,代理 啊  添加header啊  等   这里就不多写了
					if(code == 200){
						//这里直接对这个  流 进行了装饰  容易读取  数据
						BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
						
						String line = null;
						StringBuffer buffer = new StringBuffer();
						while ((line = reader.readLine())!=null) {
							buffer.append(line);
						}
						reader.close();
						//到这里 已经读取了  我们所需要的信息  如  json啊   xml 啊 (范例写的是  String 字符串类型的数据    文件 不适用)
						Message msg = Message.obtain();
						msg.what = onSuccessCode;
						msg.obj = buffer.toString();
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					//这里抛出异常 也是错误的情况  要对异常 进行处理
					Message msg = Message.obtain();
					msg.what = onEorrorCode;
					msg.arg1 = code;
					msg.obj = e.getMessage();
					handler.sendMessage(msg);
				}
			}
		}).start();
	}
	/**
	 * 设置回调接口  
	 * 当  开始  失败 成功的时候 回调这个接口
	 * 看见这个东西   应该很熟悉了吧
	 * @param listener
	 */
	public void setOnCylNetWorkListener(CylNetListener listener){
		this.listener = listener;
	}
}


default interface

2. Click test and we can get data from the network. The results are as follows:

Done. . . . . . . . .







Guess you like

Origin blog.csdn.net/tiandiyinghun/article/details/50947597