Creating a listener in an Android app

First we define the polling period.

private static long POLL_PERIOD = 20000; // period in ms.
privatestaticbooleancreated = false; // / safety check

Then, create the listener as a service. From there we call the service thread.

@Override
publicsynchronizedvoid onCreate() {
if (created) {
thrownew IllegalStateException(
"attempt to create listener twice!!");
}

created = true;
System.out.println("listener was created");
startServiceThread();
}

This thread will run the service. Has to be a thread in Android, can’t run on the main UI.

private void startServiceThread() {
new Thread(new Runnable() {
@Override
publicvoid run() {
runService();
}
}).start();
}

And here starts the endless loop of the listener. You let the thread sleep for your polling period, then you do your stuff after that call.

public void runService() {
System.out.println("listener running");
// the main loop.
while (true) {
try {
// first this, to ensure we always sleep in the loop.
Thread.sleep(POLL_PERIOD);
// do your stuff here
} catch (Throwable e) {
if (e instanceof UnknownHostException) {
System.out.println("check failed, no network");
} else {
e.printStackTrace();
}
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s