LoginSignup
5

More than 3 years have passed since last update.

[Android] コールバック

Last updated at Posted at 2020-01-24

作るもの

以下をコールバックを使って実装する。
・ボタンを押すと非同期処理を実行する
・非同期処理が終わったら画面に「終了」を表示する
スクリーンショット (4).png

用意するクラス

・AsyncTaskCallback.java  コールバックインターフェース
・MainActivity.java     コールバックインターフェースを実装する
・HttpAsync.java      非同期処理クラス

使い方

AsyncTaskCallback.java

public interface AsyncTaskCallbacks {
    public void onTaskFinished();    //終了
    public void onTaskCancelled();   //キャンセル
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements AsyncTaskCallbacks {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setAsyncButton();
    }

    private void setAsyncButton(){
        Button button = findViewById(R.id.button);
        button.setOnClickListener((View v)->{
            HttpAsync httpAsync = new HttpAsync(this);
            httpAsync.execute();  //非同期処理呼び出し
        });
    }

    @Override
    public void onTaskFinished() {
        TextView textView = findViewById(R.id.text);
        textView.setText("終了");
    }

    @Override
    public void onTaskCancelled() {
        TextView textView = findViewById(R.id.text);
        textView.setText("キャンセル");
    }
}

HttpAsync.java

public class HttpAsync extends AsyncTask<Integer, Void, Integer> {

    private AsyncTaskCallbacks callbacks_ = null;

    //コールバック登録用コンストラクタ
    public HttpAsync(AsyncTaskCallbacks _callBacks){
        this.callbacks_ = _callBacks; //コールバック登録
    }

    @Override
    protected Integer doInBackground(Integer... params) {
        //何かの処理
        return null;
    }

    @Override
    protected void onPostExecute(Integer result) {
        callbacks_.onTaskFinished(); //非同期処理が終了したらonTaskFinished()を呼ぶ
    }

    @Override
    protected void onCancelled() {
        callbacks_.onTaskCancelled(); //非同期処理がキャンセルされたらonTaskCancelled()を呼ぶ
    }
}

感想

参考URLのサイトがかなりわかりやすくて簡単に実装できた。

参考URL

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
5