Skip to content

Instantly share code, notes, and snippets.

@cofearabi
Last active December 14, 2015 04:39
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 cofearabi/5029516 to your computer and use it in GitHub Desktop.
Save cofearabi/5029516 to your computer and use it in GitHub Desktop.
Android sample using Thread, Handler
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop"
android:layout_gravity="center">
</Button>
</RelativeLayout>
package com.example.andrunnable2;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener,Runnable{
private int counter = 0;
private boolean end_flg = true;
private Button button0;
public void run() {
while(! end_flg){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
counter += 1;
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
TextView textView = (TextView) findViewById(R.id.textView0);
textView.setText("counter="+counter);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
end_flg = false;
button0=(Button)findViewById(R.id.button0);
button0.setOnClickListener(this);
Thread thread = new Thread(this);
thread.start();
}
public void onClick(View v){
end_flg=true;
//finish();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment