我已经设置了一个名为NetworkStatus
的类,用于监控设备的网络状态。在NetworkStatus
内,我定义了一个BroadcastReceiver
来监控是否存在连接更改,即互联网是否已经关闭或 on 。我想将此方法(即onReceive
)'公开'到实例化NetworkStatus
实例的活动。
我正在尝试通过在interface
类中设置NetworkStatus
来实现此目的,但我不确定如何从onReceive
方法中调用接口{ {1}}即
BroadcastReceiver
然后在主要活动中,我会做类似的事情,
public class NetworkStatus {
public static interface NetworkStatusCallbacks {
void onReceive();
}
public static class ConnectivityChange extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// need to call NetworkStatusCallbacks onReceive here
}
}
}
非常感谢一些指示。感谢。
可能的解决方案
认为我找到了解决方案。正如塞尔文指出的那样,要做到这一点需要public class MyActivity extends Activity implements NetworkStatus.NetworkStatusCallbacks {
@Override
public void onReceive() {
// Do stuff here
}
}
。因此,我通过从传递给Activity
类的构造函数的活动上下文中转换它来获取Activity
,即,将类的构造函数设置为
NetworkStatus
然后,我可以使用private static nsc NetworkStatusCallbacks;
public NetworkStatus (Context context) {
Activity activity = (Activity) context;
nsc = (NetworkStatusCallbacks) activity;
}
的{{1}}方法调用界面,如下所示:
onReceive
答案 0 :(得分:0)
尝试这样的事情:
public class NetworkStatus {
public static interface NetworkStatusCallbacks {
void onReceive();
}
private final NetworkStatusCallbacks m_cb;
NetworkStatus(NetworkStatusCallbacks cb)
{
m_cb=cb;
}
public static class ConnectivityChange extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// need to call NetworkStatusCallbacks onReceive here
m_cb.onReceive()
}
}
}