这里有两部分需要考虑:输入和输出。
用户输入
如果您的库需要处理映射到 Android 事件的事件,我将使用类似于某些现有库使用的方法,即复制方法名称和签名并返回一个 boolean 值,指示是否呼叫已被处理。
为此,创建一个类作为库和用户活动之间的桥梁,并定义以下方法:
public boolean onKeyDown (int keyCode, KeyEvent event) {
// Handle here the key event in the appropriate way
// if the pressed key was not to be handled by your library, simply return false
// else, handle it and return true
}
然后,在调用者活动中,覆盖相同的方法并适当地调用它
// We assume your bridge class is already instantiated and called `bridge`
@Override
public boolean onKeyDown (int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (bridge.onKeyDown(keyCode, event)) {
return true;
}
// User code for other keys here
}
将此模式扩展到其他方法,包括onStart 和类似的方法(如有必要)。这已被一些 Android 支持实用程序使用,例如 onOptionsItemSelected 中的 Action Bar Drawer Toggle。我个人在我的 Helpers 中使用了这种模式并且效果很好。
数据输出
根据您正在执行的处理类型,您可能希望直接通过桥接类方法或使用侦听器发布结果。
如果计算速度很快并且需要频繁但并非总是,那么使用get 方法可能会有所帮助:
public Object getResult () {
// Use an appropriate return type and method name
}
但是,如果结果因为速度慢或者只会使用一次而在单独的线程中执行,那么在处理它们时,最好使用Callbacks 类型的接口,类似于在 Loaders 框架中找到。
在你的桥接类中,定义一个这样的接口:
public class Bridge {
interface Callbacks {
void onSomeResultComputed (Object result);
void onSomeOtherResultComputed (Object result);
// etc.
}
// Other methods and fields
}
然后让客户端使用特定方法或使用遵循上述模式的onCreate 注册此回调。客户端代码如下所示
public class SomeActivity implements Bridge.Callbacks {
[...]
@Override
protected void onCreate () {
super.onCreate();
bridge.onCreate(this);
}
[...]
@Override
public void onSomeResultComputed (Object result) {
// Handle the result here
}
@Override
public void onSomeOtherResultComputed (Object result) {
// Handle the result here
}
}
同样,Google 已经在一些 Android 实用程序(例如 Loaders)和一些 Google Play 服务类中使用了这种模式,并且效果很好。
请记住,在侦听器的情况下,在并行线程中执行代价高昂的计算(可能使用AsyncTask)并始终在主线程中再次调用Callbacks 方法。