Listener implementation by:
public class MyActivity extends Activity implements Internetmanager.listener {
Private TextView MText;
Private Internetmanager minetmgr;
/* Called just like onCreate @ some point in time */
public void Onstatechange (Boolean state) {
if (state) {
Mtext.settext ("on");
} else {
Mtext.settext ("Off");
}
}
public void OnCreate () {
Minetmgr = new Internetmanager ();
Minetmgr.registerlistener (this);
Minetmgr.doyourwork ();
}
}
Custom classes, listeners as internal properties (including methods),
There is a place in the class that invokes the listener's internal methods,
Set different listener implementations, the manner of processing is not the same,
The listener is the equivalent of a hook used for callbacks.
public class Internetmanager {
All the listener stuff below
Public interface Listener {
public void Onstatechange (Boolean state);
}
Private Listener mlistener = null;
public void Registerlistener (Listener Listener) {
Mlistener = listener;
}
// -----------------------------
The part of this class does
Private Boolean Isinterneton = false;
public void Doyourwork () {
Do things here
At some point
Isinterneton = true;
Now notify if someone is interested.
if (Mlistener! = null)
Mlistener.onstatechange (Isinterneton);
}
}
Example two:
@Override
public void OnStart (Intent Intent, int startid) {
Super.onstart (Intent, Startid);
Locationservice = ((locationapplication) getapplication ()). Locationservice;
To get an Locationservice instance, it is recommended that only 1 location instances be initialized in the app, and then used, to refer to the activity of other examples, all of which get the Locationservice instance's
Locationservice.registerlistener (Mlistener); Register for monitoring
if (type = = 0) {
Locationservice.setlocationoption (Locationservice.getdefaultlocationclientoption ());
} else if (type = = 1) {
Locationservice.setlocationoption (Locationservice.getoption ());
}
}
@Override
public void OnDestroy () {
LOG.I ("Warn", "OnDestroy");
Locationservice.stop (); Stop Location Services
Locationservice.unregisterlistener (Mlistener); Log out of the monitor
}
Java Listener Implementation principle