56
53

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AsyncTaskにリスナーを追加してActivityで処理する

Posted at

原型のAsyncTask

AsyncTaskSample

public class AsyncTaskSample extends AsyncTask<Void, Integer, String> {
	//Activiyへのコールバック用interface
	public interface AsyncTaskCallback {
		void preExecute();
		void postExecute(String result);
		void progressUpdate(int progress);
		void cancel();
	}

	private AsyncTaskCallback callback = null;;

	public AsyncTaskSample(AsyncTaskCallback _callback) {
		this.callback = _callback;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		callback.preExecute();
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		callback.cancel();
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		callback.postExecute(result);
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		callback.progressUpdate(values[0]);
	}

	@Override
	protected String doInBackground(Void... params) {
		return null;
	}
}

(空行)
実装するActivity

Activity
public class SampleActivity {
	public void onCreate(Bundle savedInstanceState) {
		AsyncTaskSample sampleTask = new AsyncTaskSample(new AsyncTaskCallback() {
			public void preExecute() {
				//だいたいの場合ダイアログの表示などを行う
			}
			public void postExecute(String result) {
				//AsyncTaskの結果を受け取ってなんかする
			}
			public void progressUpdate(int progress) {
				//だいたいプログレスダイアログを進める
			}
			public void cancel() {
				//キャンセルされた時になんかする
			}
		});
	 	sampleTask.execute();
	}
}

または

Activity
public class SampleActivity implements AsyncTaskCallback {
	public void onCreate(Bundle savedInstanceState) {
		AsyncTaskSample sampleTask = new AsyncTaskSample(this);
		sampleTask.execute();
	}
	public void preExecute() {
		//だいたいの場合ダイアログの表示などを行う
	}
	public void postExecute(String result) {
		//AsyncTaskの結果を受け取ってなんかする
	}
	public void progressUpdate(int progress) {
		//だいたいプログレスダイアログを進める
	}
	public void cancel() {
		//キャンセルされた時になんかする
	}
}
56
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
53

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?