AsyncTaskを使った非同期処理中にプログレスダイアログを表示する (SPINNER)
メモ。
package com.freefly3104.satoshi.myasynctask01; import android.app.Dialog; import android.app.DialogFragment; import android.app.ProgressDialog; import android.os.Bundle; public class SpinningProgressDialog extends DialogFragment { private ProgressDialog progressDialog; public static SpinningProgressDialog newInstance(int title, int message) { SpinningProgressDialog fragment = new SpinningProgressDialog(); Bundle args = new Bundle(); args.putInt("title", title); args.putInt("message", message); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle safedInstanceState) { int title = getArguments().getInt("title"); int message = getArguments().getInt("message"); progressDialog = new ProgressDialog(getActivity()); progressDialog.setTitle(title); progressDialog.setMessage(getResources().getText(message)); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); return progressDialog; } }
package com.freefly3104.satoshi.myasynctask01; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; public class MyAsyncTask extends AsyncTask<String, Integer, Long>{ private Context context; SpinningProgressDialog progressDialog = null; public MyAsyncTask(Context context) { this.context = context; } /** * バッググラウンド処理の前処理(準備) * UI Thread処理 */ @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = SpinningProgressDialog.newInstance(R.string.pb_title, R.string.pb_message); progressDialog.show(((Activity) context).getFragmentManager(), "progress"); } /** * バックグラウンド処理 */ @Override protected Long doInBackground(String... params) { try{ // 確認の為、10秒待ちます Thread.sleep(10000); } catch (InterruptedException e) { Log.d("test", "Error"); } return 123L; } /** * バックグラウンド処理が終わった後の処理(表示の更新) */ @Override protected void onPostExecute(Long result) { super.onPostExecute(result); if (progressDialog.getShowsDialog()) progressDialog.dismiss(); if (result != null){ Toast.makeText(context, result.toString(), Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "NG", Toast.LENGTH_SHORT).show(); } } }
package com.freefly3104.satoshi.myasynctask01; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.button1); // クリック処理(匿名クラス) btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // AsyncTask呼び出し new MyAsyncTask(MainActivity.this).execute("params"); } }); } }