Created
March 16, 2016 10:39
-
-
Save hiq-larryschiefer/956b572a1753b4ab741b to your computer and use it in GitHub Desktop.
Android HandlerThread example usage
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
public class SampleActivity extends Activity implements Handler.Callback { | |
private static final int MSG_START_OP = 1; | |
private static final int MSG_PAUSE_OP = 2; | |
private static final int MSG_SEND_ALIVE_OP = 3; | |
private HandlerThread mHT; | |
private Handler mMsgHandler; | |
@Override | |
void onCreate(Bundle savedInstance) { | |
super.onCreate(savedInstance); | |
setContextView(R.layout.sample_activity); | |
// Other setup | |
mHT = new HandlerThread("Bg Msg Thread"); | |
mHT.start(); | |
mMsgHandler = new Handler(mHT.getLooper(), this); | |
} | |
@Override | |
void onResume() { | |
mMsgHandler.sendEmptyMessage(MSG_START_OP); | |
} | |
@Override | |
void onPause() { | |
// Pause the POST messages | |
mMsgHandler.sendEmptyMessage(MSG_PAUSE_OP); | |
} | |
@Override | |
void onDestroy() { | |
// Stop our bg thread | |
mHT.quitSafely(); | |
} | |
// Handler.Callback implementation | |
@Override | |
boolean handleMessage(Message msg) { | |
switch (msg.what) { | |
case MSG_START_OP: | |
mMsgHandler.sendEmptyMessageDelayed(MSG_SEND_ALIVE_OP, ALIVE_INTERVAL); | |
break; | |
case MSG_STOP_OP: | |
mMsgHandler.removeMessages(MSG_SEND_ALIVE_OP); | |
mMsgHandler.removeMessages(MSG_START_OP); | |
break; | |
case MSG_SEND_ALIVE_OP: | |
// Do POST request | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment