Created
July 30, 2014 11:16
-
-
Save rileyrg/c8cf90db04a8d7b90dc1 to your computer and use it in GitHub Desktop.
using interfaces for callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Create an interface to describe the "callbacks" available on my main activity so that a worker thread can callback and have the activity update certain mainthread views. | |
,---- | |
| public interface HoneyBeezListener { | |
| public void frameRate(int frameCount); | |
| /* add other callbacks here */ | |
| } | |
`---- | |
In my customview create a holder for the callback interface and a setter | |
,---- | |
| private HoneyBeezListener honeyBeezListener; | |
| | |
| public void setHoneyBeezListener(HoneyBeezListener listener) { | |
| honeyBeezListener = listener; | |
| } | |
`---- | |
In my main acitivity which manages various mainthread views assign a listener to my customview so it can callback. | |
,---- | |
| gardenView.setHoneyBeezListener(new HoneyBeezListener() { | |
| @Override | |
| public void frameRate(int frameCount) { | |
| displayFrameRate(frameCount); | |
| } | |
| }); | |
`---- | |
also define the function to update a mainthread frame rate view in the mainactivity: (yes not optimised) | |
,---- | |
| private void displayFrameRate(int frameRate) { | |
| ((TextView) findViewById(R.id.framerate)).setText(getString(R.string.framerate) + frameRate); | |
| } | |
`---- | |
when we want to callback we create a runnable an post back to the mainuithread | |
,---- | |
| if (curTime >= lastFrameTime + 1000) { /* frames per second */ | |
| lastFrameTime = curTime; | |
| ((Activity)context).runOnUiThread(new Runnable() { | |
| int f=frameCount; | |
| @Override | |
| public void run() { | |
| honeyBeezListener.frameRate(f); | |
| } | |
| }); | |
| frameCount = 0; | |
| } | |
`---- | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment