Created
September 17, 2014 03:08
-
-
Save garymabin/f4a5072a679f37bb6ccd to your computer and use it in GitHub Desktop.
Code for switching data between work thread and main thread using Handler.post()
This file contains hidden or 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
public interface INotifier { | |
void onNewData(Object payload); | |
} |
This file contains hidden or 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
public class WorkThread { | |
private INotifier mNotifier; | |
public void run() { | |
Object payload; | |
//do your network relate stuff | |
mNotifier.onNewData(payload); | |
} | |
} |
This file contains hidden or 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
public class WorkTracker implements INotifier { | |
private Handler mHandler = new Handler(); | |
static class NotifyRunnable implements Runnable { | |
private Object mPayload; | |
public NotifyRunnable(Object data) { | |
mPayload = data; | |
} | |
public void run() { | |
//when post to hanlder based on main looper, now we run on main thread. | |
} | |
} | |
public void onNewData(Object payload) { | |
//called on WorkThread, use Handler to change to main thred. | |
mHandler.post(new NotifyRunnable(payload)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment