サブスレッドからメインのUIスレッドを操作する

ここを参考に。
http://techbooster.jpn.org/andriod/application/6191/

このページだと同一クラスで別スレを走らせてたけど
別クラスに分けてやる方法を試してみた。

MainActivity.java

package com.example.threadactivity;

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

public class MainActivity extends Activity {

	volatile SubThread mLooper;
	Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		final TextView tv = (TextView) findViewById(R.id.textView);
		mHandler = new Handler() {
			public void handleMessage(Message message) {
				tv.setText((String) message.obj);
			};
		};
	}

	@Override
	protected void onStart() {
		super.onStart();
		mLooper = new SubThread(this);
		if (mLooper != null) {
			mLooper.start();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		mLooper = null;
	}

}

SubThread.java

package com.example.threadactivity;

import android.os.Handler;
import android.os.Message;

public class SubThread extends Thread {
	MainActivity mActivity;
	Handler mHandler;

	SubThread(MainActivity main) {
		mActivity = main;
		mHandler = mActivity.mHandler;
	}

	@Override
	public void run() {
		long time = System.currentTimeMillis();
		long count = 0;
		while (mActivity.mLooper != null) { //while(this != null)のこと
			long now = System.currentTimeMillis();
			if (now - time > 1000) {
				Message msg = Message.obtain(); // 推奨
				msg.obj = new String("ループが" + count + "回終了しました");
				mHandler.sendMessage(msg);
				time = now;
				count++;
			}
		}
	}
}