Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Created February 23, 2012 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daichan4649/1889951 to your computer and use it in GitHub Desktop.
Save daichan4649/1889951 to your computer and use it in GitHub Desktop.
HandlerThread
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main" />
<Button
android:id="@+id/other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="other" />
</LinearLayout>
package test.handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//------------------------------------
// UI-Thread
//------------------------------------
// Handler(for UI-Thread)
final Handler mainHandler = new Handler();
findViewById(R.id.main).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mainHandler.post(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
});
//------------------------------------
// Other-Thread
//------------------------------------
// start Other-Thrad
HandlerThread handlerThread = new HandlerThread("other");
handlerThread.start();
// Handler(for Other-Thread)
final Handler otherHandler = new Handler(handlerThread.getLooper());
findViewById(R.id.other).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
otherHandler.post(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment