简体   繁体   中英

How to Interface onReceive Method

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, ie, if the internet has been switched off or on . I want to 'expose' this method (ie 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 ie,

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, ie, 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();
}

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM