概述
接口回调其本质与上转型是一样的,不同的是:接口回调是用接口句柄来得到并调用实现这个接口的子类的引用;而上转型则是用父类句柄来得到并调用继承此父类的子类的引用。
实例
- 创建一个接口:
public interface MyBroadcastListener{
void doSomething(String value);
}
- 在您的 BroadcastReceiver 中初始化监听器
public class MyReceiver extends BroadcastReceiver {
private MyBroadcastListener listener;
public MyReceiver(MyBroadcastListener listener){
this.listener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
listener.doSomething("Some Result");
}
}
- 在您的 Activity 中实现接口并重写方法
public MainActivity extends AppCompatActivity implements MyBroadcastListener{
private BroadcastReceiver receiver;
@Override
public void onCreate(Bundle sis){
// Related code
receiver = new MyReceiver(this); // This is how you initialise receiver
// 注册广播
...
}
public void updateUI(String msg) {
TextView textView = (TextView) findViewById(R.id.textView);
textView .setText(msg);
}
@Override
public void doSomething(String result){
updateUI(result); // Calling method from Interface
}
}
网友评论