Last active
December 14, 2015 04:39
-
-
Save cofearabi/5029516 to your computer and use it in GitHub Desktop.
Android sample using Thread, Handler
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
<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> |
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
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