Last active
August 29, 2015 14:25
-
-
Save SelvinPL/eaf75cf244df4d2f2ee6 to your computer and use it in GitHub Desktop.
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 TestActivity extends Activity { | |
| final Object uiHandlerLock = new Object(); | |
| Button butt; | |
| HandlerThread thread; | |
| Handler backgroundHandler; | |
| Handler uiHandler; | |
| @Override | |
| protected void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| butt = new Button(this); | |
| butt.setText("Click me"); | |
| butt.setOnClickListener(new View.OnClickListener() { | |
| @Override | |
| public void onClick(View v) { | |
| backgroundHandler.post(new Runnable() { | |
| @Override | |
| public void run() { | |
| try { | |
| Log.i("TAG", "the job started! Thread:" + Thread.currentThread().getId()); | |
| //do the job on background | |
| Thread.sleep(1500); | |
| synchronized (uiHandlerLock) { | |
| if (uiHandler != null) | |
| //report back on Ui thread | |
| uiHandler.post(new Runnable() { | |
| @Override | |
| public void run() { | |
| Log.i("TAG", "the job done! Thread: " + Thread.currentThread().getId()); | |
| } | |
| }); | |
| } | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| }); | |
| } | |
| }); | |
| setContentView(butt); | |
| } | |
| @Override | |
| protected void onResume() { | |
| super.onResume(); | |
| thread = new HandlerThread("test"); | |
| thread.start(); | |
| uiHandler = new Handler(); | |
| backgroundHandler = new Handler(thread.getLooper()); | |
| Log.i("TAG", "start UiThread:" + Thread.currentThread().getId()); | |
| } | |
| @Override | |
| protected void onPause() { | |
| super.onPause(); | |
| synchronized (uiHandlerLock) { | |
| uiHandler = null; | |
| } | |
| if (thread != null) { | |
| thread.quit(); | |
| Log.i("TAG", "quit"); | |
| } | |
| thread = null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment