AndroidRunnable, with Runnable Thread.

It's a very simple exercise to implament a activity with a Runnable Thread.



Modify main.xml to add a TextView, as a counter used to monitor the Runnable Thread. It count-up in every 1000ms.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/i"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


Modify AndroidRunnable.java
package com.exercise.AndroidRunnable;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class AndroidRunnable extends Activity{

int i = 0;
TextView myi;

Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
update_i();
}
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

myi =(TextView)findViewById(R.id.i);
}

@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();

Thread myThread=new Thread(new Runnable() {
public void run() {
while(true){
try {
handler.sendMessage(handler.obtainMessage());
Thread.sleep(1000);
}
catch (Throwable t) {
}
}
}
});

myThread.start();
}

private void update_i()
{
i++;
myi.setText(String.valueOf(i));
}
}

AndroidRunnable.java can be downloaded here.

Note that update_i() cannot be called inside myThread directly, because only the Thread create the View can touch it. Otherwise, Exception will be generated. That's why I have to implement a Handler to call update_i() indirectly.

0 Response to "AndroidRunnable, with Runnable Thread."

Post a Comment