「android開発」ThreadとHandlerでマルチスレッド処理するサンプルコード

サンプルコード:
package com.startnews24.handler;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private Button btn_show;
private TextView tv_show;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn_show = (Button)findViewById(R.id.btn_show);
tv_show = (TextView)findViewById(R.id.tv_show);

btn_show.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
thread.start();
}
});
System.out.println(“親スレッド:" + Thread.currentThread().getName());
}

private Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 5){
tv_show.setText(“子スレッドのメッセージを取得");
}
}
};

private Thread thread = new Thread(){

@Override
public void run() {
super.run();
try {
thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = handler.obtainMessage();
msg.what = 5;
System.out.println(“子スレッド:"+
thread.currentThread().getName());
handler.sendMessage(msg);
}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Android

Posted by arkgame