
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class AndroidAsyncTaskActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void buttonClick(View v) {
Log.d("タグ", "ボタンがクリックした。!");
new MyAsyncTask(this).execute("Param1");
}
public class MyAsyncTask extends AsyncTask<String, Integer, Long> implements OnCancelListener {
private Context context;
private ProgressDialog dialog;
public MyAsyncTask(Context context) {
// TODO 自動生成されたコンストラクター・スタブ
this.context = context;
}
@Override
protected void onPreExecute() {
// タスク開始前処理:UIスレッドで実行される
//進捗ダイアログの表示
Log.d("TAG", "onPreExecute");
dialog = new ProgressDialog(context);
dialog.setTitle("しばらくお待ちください");
dialog.setMessage("データ読み込み中...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(true);// ProgressDialog のキャンセルが可能かどうか
dialog.setOnCancelListener(this);
dialog.setMax(100);
dialog.setProgress(0);
// ProgressDialog の Cancel ボタン
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "キャンセル", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// ProgressDialog をキャンセル
dialog.cancel();
}
});
dialog.show();
}
@Override
protected Long doInBackground(String... params) {
// 別スレッドで実行する処理
Log.d("", "doInBackground ::" + params[0]);//doInBackground ::Param1
try {
for (int i = 0; i < 10; i++) {
if (isCancelled()) {
Log.d("", "Cancelled!");
break;
}
Thread.sleep(1000);
publishProgress((i + 1) * 10);
}
} catch (InterruptedException e) {
Log.d("", "InterruptedException in doInBackground");
}
return 999L;
}
// プログレスバー更新処理: UIスレッドで実行される
@Override
protected void onProgressUpdate(Integer... values) {
Log.d("", "onProgressUpdate ::" + values[0]);
dialog.setProgress(values[0]);
}
@Override
protected void onCancelled() {
Log.d("", "onCancelled");
dialog.dismiss();
}
@Override
protected void onPostExecute(Long result) {
// タスク終了後処理:UIスレッドで実行される
Log.d("", "onPostExecute :: " + result);//doInBackground のリターン
// 進捗ダイアログをクローズ
dialog.dismiss();
}
public void onCancel(DialogInterface dialog) {
Log.d("", "Dialog onCancell... calling cancel(true)");
this.cancel(true);
}
}
}
07-23 20:52:59.493: D/(12475): onProgressUpdate ::50
07-23 20:53:00.509: D/(12475): onProgressUpdate ::60
07-23 20:53:01.163: D/(12475): Dialog onCancell... calling cancel(true)
07-23 20:53:01.163: D/(12475): InterruptedException in doInBackground
07-23 20:53:01.173: D/(12475): onCancelled
0 件のコメント:
コメントを投稿