[英]How to Interface onReceive Method
I've set up a class called NetworkStatus
that monitors the network status of the device. 我已经建立了一个名为NetworkStatus
的类,该类监视设备的网络状态。 Within NetworkStatus
I've defined a BroadcastReceiver
that monitors if there has been a connectivity change, ie, if the internet has been switched off or on . 在NetworkStatus
我定义了一个BroadcastReceiver
,它监视连接性是否发生了变化,即,互联网是关闭还是打开 。 I want to 'expose' this method (ie onReceive
) to the activity that instantiated the instance of NetworkStatus
. 我想将此方法(即onReceive
)“公开”给实例化NetworkStatus
实例的活动。
I'm trying to achieve this by setting up an interface
in the NetworkStatus
class, but I'm not sure how to call the interface from the onReceive
method of the BroadcastReceiver
ie, 我试图通过在NetworkStatus
类中设置一个interface
来实现此目的,但是我不确定如何从BroadcastReceiver
的onReceive
方法调用该接口,即,
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
}
}
}
Then in the main activity I would do something like, 然后在主要活动中,我会做类似的事情,
public class MyActivity extends Activity implements NetworkStatus.NetworkStatusCallbacks {
@Override
public void onReceive() {
// Do stuff here
}
}
Would really appreciate some pointers. 非常感谢您提供一些指导。 Thanks. 谢谢。
Possible Solution 可能的解决方案
Think I have found a solution. 想我已经找到了解决方案。 As Selvin pointed out, to do this requires the Activity
. 正如Selvin指出的那样,要做到这一点就需要Activity
。 I therefore obtained the Activity
by casting it from the activity context that is passed to a constructor for the NetworkStatus
class, ie, setting a constructor for the class as 因此,我通过从传递给NetworkStatus
类的构造函数的活动上下文进行强制转换来获得Activity
,即,将该类的构造函数设置为
private static nsc NetworkStatusCallbacks;
public NetworkStatus (Context context) {
Activity activity = (Activity) context;
nsc = (NetworkStatusCallbacks) activity;
}
I can then call the interface from the onReceive
method of the BroadcastReceiver
as follows: 然后,我可以从BroadcastReceiver
的onReceive
方法调用该接口,如下所示:
public void onReceive(Context context, Intent intent) {
nsc.onReceive();
}
Try something like this: 尝试这样的事情:
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()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.