2

I've set up a class called NetworkStatus that monitors the network status of the device. Within NetworkStatus I've defined a BroadcastReceiver that monitors if there has been a connectivity change, i.e., if the internet has been switched off or on. I want to 'expose' this method (i.e. onReceive) to the activity that instantiated the instance of 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 i.e.,

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. I therefore obtained the Activity by casting it from the activity context that is passed to a constructor for the NetworkStatus class, i.e., setting a constructor for the class as

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:

public void onReceive(Context context, Intent intent) {
    nsc.onReceive();
}
4

1 回答 1

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

    }
于 2013-08-28T12:25:14.460 回答