http://android.keicode.com/basics/async-asynctask.php
Android で重い処理を行う場合は、AsyncTask を使うと良い。
非同期処理を開始
1 |
package com.keicode.android.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class AsyncTest2 extends Activity implements OnClickListener { final String TAG = "AsyncTest2"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Button)findViewById(R.id.button1)) .setOnClickListener(this); } @Override public void onClick(View v) { if(v.getId() == R.id.button1){ new MyAsyncTask(this).execute("Param1"); } } } |
非同期処理のメイン
extends AsyncTask<String, Integer, Long>
の後ろ(ダイアモンド演算子)はそれぞれ
doInBackground onProgressUpdate onPostExecute
に渡す引数の型を指定している。
処理のキャンセルは、
isCanceled
をループ内で呼び出して、キャンセルされていたらループを抜けるようにするとよい。
1 |
package com.keicode.android.test; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.util.Log; public class MyAsyncTask extends AsyncTask<String, Integer, Long> implements OnCancelListener{ final String TAG = "MyAsyncTask"; ProgressDialog dialog; Context context; public MyAsyncTask(Context context){ this.context = context; } @Override protected void onPreExecute() { Log.d(TAG, "onPreExecute"); dialog = new ProgressDialog(context); dialog.setTitle("Please wait"); dialog.setMessage("Loading data..."); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setCancelable(true); dialog.setOnCancelListener(this); dialog.setMax(100); dialog.setProgress(0); dialog.show(); } @Override protected Long doInBackground(String... params) { Log.d(TAG, "doInBackground - " + params[0]); try { for(int i=0; i<10; i++){ if(isCancelled()){ Log.d(TAG, "Cancelled!"); break; } Thread.sleep(1000); publishProgress((i+1) * 10); } } catch (InterruptedException e) { Log.d(TAG, "InterruptedException in doInBackground"); } return 123L; } @Override protected void onProgressUpdate(Integer... values) { Log.d(TAG, "onProgressUpdate - " + values[0]); dialog.setProgress(values[0]); } @Override protected void onCancelled() { Log.d(TAG, "onCancelled"); dialog.dismiss(); } @Override protected void onPostExecute(Long result) { Log.d(TAG, "onPostExecute - " + result); dialog.dismiss(); } @Override public void onCancel(DialogInterface dialog) { Log.d(TAG, "Dialog onCancell... calling cancel(true)"); //this.cancel(true); this.cancel(false); } } |
[カテゴリ: プログラミング言語 > Java > Android]
[通知用URL]
Tweet
最終更新時間:2013年02月20日 01時22分58秒