Created
September 30, 2013 11:20
-
-
Save shikajiro/6762401 to your computer and use it in GitHub Desktop.
スレッドとハンドラーのサンプル
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.study0930; | |
import android.app.Activity; | |
import android.app.ProgressDialog; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.util.Log; | |
import android.view.Menu; | |
import android.view.View; | |
import android.view.View.OnClickListener; | |
import android.widget.Button; | |
import android.widget.Toast; | |
public class MainActivity extends Activity { | |
private long total = 0; | |
private Handler handler = new Handler(); | |
private ProgressDialog progressDialog; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
Button button = (Button) findViewById(R.id.button1); | |
button.setOnClickListener(new OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
progressDialog = ProgressDialog.show( | |
MainActivity.this, | |
"複雑な処理中です", | |
"しばらくお待ち下さい"); | |
//スレッドを作って、重たい処理はお任せする。 | |
Runnable runnable = new Runnable() { | |
public void run() { | |
//大変複雑な処理とかが行われるに違いない | |
for(int i=0; i<10000000; i++){ | |
total += i; | |
} | |
progressDialog.dismiss(); | |
Runnable resultRunnable = new Runnable() { | |
public void run() { | |
//結果を画面に表示 | |
Toast.makeText( | |
MainActivity.this, | |
"合計は"+total+"でした。", | |
Toast.LENGTH_LONG).show(); | |
} | |
}; | |
handler.post(resultRunnable); | |
} | |
}; | |
Thread thread = new Thread(runnable); | |
thread.start(); | |
Toast.makeText( | |
MainActivity.this, | |
"スレッドが計算を始めました", | |
Toast.LENGTH_SHORT).show(); | |
} | |
}); | |
} | |
@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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment