Android多线程开发之Callback
多线程中的返回Callback---回调interface
Callback
javax.security.auth.callback.Callback
Known Direct Subclasses
PasswordCallback
Implementations of this interface are passed to a CallbackHandler, allowing underlying security services the ability to interact with a calling application to retrieve specific authentication data such as usernames and passwords, or to display certain information, such as error and warning messages.Callback implementations do not retrieve or display the information requested by underlying security services. Callback implementations simply provide the means to pass such requests to applications, and for applications, if appropriate, to return requested information back to the underlying security services.
做Android开发的,道友们应该经常会遇到用多线程处理问题,在顺序执行的函数中,return得到一个想要的结果是一件美事,但如果我们要从多线程中返回一个结果怎么办呢?
直接return明显不可能。
此时我们需要用到多线程中的返回Callback---回调。
interface
interface是面向对象编程语言中接口操作的关键字,功能是把所需成员组合起来,用来封装一定功能的集合。它好比一个模板,在其中定义了对象必须实现的成员,通过类或结构来实现它。接口不能直接实例化,即ICount ic=new iCount()是错的。接口不能包含成员的任何代码,只定义成员本身。接口成员的具体代码由实现接口的类提供。接口使用interface关键字进行声明。
实现方式如下
public interface OnResultCallback{
void onComplete(Object object);
void onError(int code);
}
这里我们随便写了一个接口,接口中有两个方法。如果需要回调的情况有多种,可以在接口中添加每种情况的方法作为返回。
用法
public class DemoThread extends Thread {
private final OnResultCallback callback;
public DemoThread(OnResultCallback callback) {
this.callback = callback;
}
@Override
public void run() {
super.run();
//当多线程中操作完成后可在此处回调想要的结果
if (callback != null) {
callback.onComplete(null);
}
//异常情况下的处理
if (callback != null) {
callback.onError(-1);
}
}
public interface OnResultCallback {
void onComplete(Object object);
void onError(int code);
}
}
这里接口我们放到DemoThread .class中,也可以单独新建一个类,作为接口类来处理。
DemoThread demoThread = new DemoThread(new DemoThread.OnResultCallback() {
@Override
public void onComplete(Object object) {
//得到了想要的结果
}
@Override
public void onError(int code) {
//异常返回
}
});
demoThread.start();
有些关键字如果了解不够,可以去官网或者更专业的博客找寻答案。
更多推荐
所有评论(0)