「Android/マルチスレッド」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→サンプルソース) |
(→サンプルソース(toastなどを使う場合)) |
||
| 行20: | 行20: | ||
}); | }); | ||
}).start(); | }).start(); | ||
| + | |||
| + | ==秒カウント処理== | ||
| + | |||
| + | protected void onCreate(Bundle savedInstanceState) { | ||
| + | super.onCreate(savedInstanceState); | ||
| + | setContentView(R.layout.activity_main); | ||
| + | Button btn = (Button)findViewById(R.id.button01); | ||
| + | btn.setText("please,click"); | ||
| + | btn.setOnClickListener(new View.OnClickListener() { | ||
| + | public void onClick(View v) { | ||
| + | ThreadSample thread = new ThreadSample(); | ||
| + | thread.start(); | ||
| + | Log.i("threadexec", "ThreadSample処理開始"); | ||
| + | try { | ||
| + | thread.join(); // Threadが終わるまで待機 | ||
| + | // thread.join(2000); // 処理開始から2秒間待機だけ | ||
| + | } catch (InterruptedException e) { | ||
| + | e.printStackTrace(); | ||
| + | } | ||
| + | Log.i("threadexec", "ThreadSample処理終了"); | ||
| + | } | ||
| + | }); | ||
| + | } | ||
| + | public class ThreadSample extends Thread { | ||
| + | public void run(){ | ||
| + | for (int i = 0; i < 5; i++) { | ||
| + | try { | ||
| + | Thread.sleep(1000); // 1秒待機 | ||
| + | Log.i("threadexec", (i + 1) + "秒経過"); | ||
| + | } catch (InterruptedException e) { | ||
| + | e.printStackTrace(); | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | |||
| + | レイアウト | ||
| + | <Button | ||
| + | android:text="Button" | ||
| + | android:layout_width="wrap_content" | ||
| + | android:layout_height="wrap_content" | ||
| + | android:id="@+id/button01"> | ||
| + | </Button> | ||
2018年10月25日 (木) 15:06時点における版
サンプルソース
// マルチスレッドロード
new Thread(new Runnable() {
@Override
public void run() {
// ここにロジックを書く
}
}).start();
サンプルソース(toastなどを使う場合)
// マルチスレッドロード
new Thread(new Runnable() {
// マルチスレッド内でtoastなどを使う場合はこちらに記述
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
}
});
}).start();
秒カウント処理
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button01);
btn.setText("please,click");
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ThreadSample thread = new ThreadSample();
thread.start();
Log.i("threadexec", "ThreadSample処理開始");
try {
thread.join(); // Threadが終わるまで待機
// thread.join(2000); // 処理開始から2秒間待機だけ
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("threadexec", "ThreadSample処理終了");
}
});
}
public class ThreadSample extends Thread {
public void run(){
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000); // 1秒待機
Log.i("threadexec", (i + 1) + "秒経過");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
レイアウト
<Button android:text="Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button01"> </Button>
