Android多线程开发之Callback

48 篇文章 2 订阅

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();

有些关键字如果了解不够,可以去官网或者更专业的博客找寻答案。

  • 31
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会写代码的猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值