AndroidのAsyncTaskの例のチュートリアル

今日はAndroid AsyncTaskについて見ていきます。バックグラウンドで抽象的なAsyncTaskを実行するAndroidのサンプルアプリケーションを開発します。

AndroidのAsyncTask

Android AsyncTaskは、Androidが提供する抽象クラスであり、重いタスクをバックグラウンドで実行し、UIスレッドを軽量に保ち、アプリケーションをよりレスポンシブにする自由を与えてくれます。Androidアプリケーションは起動時に単一のスレッド上で実行されます。この単一スレッドモデルのため、応答を取得するのに時間がかかるタスクは、アプリケーションが非応答になる可能性があります。これを回避するために、android AsyncTaskを使用して重いタスクを専用スレッドでバックグラウンドで実行し、結果をUIスレッドに戻します。そのため、AndroidアプリケーションでAsyncTaskを使用することで、UIスレッドを常にレスポンシブに保つことができます。 android AsyncTaskクラスで使用される基本的なメソッドは以下の通りです:

  • doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements
  • onPreExecute() : This method contains the code which is executed before the background processing starts
  • onPostExecute() : This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method
  • onProgressUpdate() : This method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update the UI thread

AndroidのAsyncTaskクラスで使用される3つの一般的なタイプは以下の通りです。

  • Params : The type of the parameters sent to the task upon execution
  • Progress : The type of the progress units published during the background computation
  • Result : The type of the result of the background computation

AndroidのAsyncTaskの例

AsyncTaskを開始するためには、次のスニペットがMainActivityクラスに含まれている必要があります。

MyTask myTask = new MyTask();
myTask.execute();

上記のスニペットでは、AsyncTaskを拡張したサンプルクラス名を使用し、executeメソッドがバックグラウンドスレッドを開始するために使用されています。注意:

  • The AsyncTask instance must be created and invoked in the UI thread.
  • The methods overridden in the AsyncTask class should never be called. They’re called automatically
  • AsyncTask can be called only once. Executing it again will throw an exception

このチュートリアルでは、ユーザーが設定した一定の時間だけプロセスをスリープさせるAsyncTaskを実装します。

Android Async Taskのプロジェクト構造

AndroidのAsyncTaskの例のコード

activity_main.xmlには、XMLレイアウトが定義されており、以下に記載されています。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="9dip"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="10dip"
        android:text="Sleep time in Seconds:"/>
    <EditText
        android:id="@+id/in_time"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_time"
        android:layout_alignTop="@id/tv_time"
        android:inputType="number"
        />
    <Button
        android:id="@+id/btn_run"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Run Async task"
        android:layout_below="@+id/in_time"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="64dp" />
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="7pt"
        android:layout_below="@+id/btn_run"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

上記のレイアウトでは、EditTextの枠として事前定義されたdrawableを使用しています。MainActivity.javaは以下で定義されています。

package com.scdev.asynctask;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private EditText time;
    private TextView finalResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        time = (EditText) findViewById(R.id.in_time);
        button = (Button) findViewById(R.id.btn_run);
        finalResult = (TextView) findViewById(R.id.tv_result);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = time.getText().toString();
                runner.execute(sleepTime);
            }
        });
    }

    private class AsyncTaskRunner extends AsyncTask<String, String, String> {

        private String resp;
        ProgressDialog progressDialog;

        @Override
        protected String doInBackground(String... params) {
            publishProgress("Sleeping..."); // Calls onProgressUpdate()
            try {
                int time = Integer.parseInt(params[0])*1000;

                Thread.sleep(time);
                resp = "Slept for " + params[0] + " seconds";
            } catch (InterruptedException e) {
                e.printStackTrace();
                resp = e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
            }
            return resp;
        }


        @Override
        protected void onPostExecute(String result) {
            // execution of result of Long time consuming operation
            progressDialog.dismiss();
            finalResult.setText(result);
        }


        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this,
                    "ProgressDialog",
                    "Wait for "+time.getText().toString()+ " seconds");
        }


        @Override
        protected void onProgressUpdate(String... text) {
            finalResult.setText(text[0]);
            
        }
    }
}

上記のコードでは、AsyncTaskRunnerクラスを使用してAsyncTaskの操作を実行しました。秒数はパラメータとしてクラスに渡され、指定された時間の間、プログレスダイアログが表示されます。以下に表示される画像は、ユーザーが設定した時間が5秒の場合に生成される出力です。これでチュートリアルは終了です。最終的なAndroid AsyncTaskプロジェクトは、以下のリンクからダウンロードできます。

AndroidのAsyncTaskの例プロジェクトをダウンロードしてください。

コメントを残す 0

Your email address will not be published. Required fields are marked *