Last active
December 24, 2015 07:19
-
-
Save shikajiro/6762871 to your computer and use it in GitHub Desktop.
AsyncTaskのサンプル
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.AsyncTask; | |
import android.os.Bundle; | |
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 { | |
@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) { | |
AsyncTask<Void, Integer, Long> asyncTask = new AsyncTask<Void/*引数の型*/, Integer/*ダイアログのパーセントとかに使う型*/, Long/*doInBackgroundの結果*/>() { | |
private ProgressDialog progressDialog; | |
// 前処理 UIスレッド | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
progressDialog = ProgressDialog.show(MainActivity.this, | |
"複雑な処理中です", "しばらくお待ち下さい"); | |
} | |
// このメソッドは別スレッド | |
@Override | |
protected Long doInBackground(Void... params) { | |
// 大変複雑な処理とかが行われるに違いない | |
long total = 0; | |
for (int i = 0; i < 10000000; i++) { | |
total += i; | |
} | |
return total; | |
} | |
// 後処理 UIスレッド | |
@Override | |
protected void onPostExecute(Long result) { | |
super.onPostExecute(result); | |
progressDialog.dismiss(); | |
// 結果を画面に表示 | |
Toast.makeText(MainActivity.this, | |
"合計は" + result + "でした。", Toast.LENGTH_LONG) | |
.show(); | |
} | |
}; | |
asyncTask.execute(); | |
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