LoginSignup
7
9

More than 5 years have passed since last update.

Android で非同期でファイル一覧みたいなもののサムネイル表示する例 ThreadPoolExecutor を使う場合

Last updated at Posted at 2014-04-19

ThreadPoolExecutor を使ってサムネイル表示する例

ぜんてい

  1. 非同期でやりたい
  2. サムネイル用の画像ファイル自体が無い場合も想定
  3. ImageView に画像を表示
  4. ネットワーク通信はしない

ポイント

  1. ThreadPoolExecutor を使うよ
  2. LinkedBlockingQueue がベストなのかわからん
  3. 非同期だから WeakReference 使うよ

ソース

ThreadPoolExecutor を用意するメソッド

    /**
     * thumbnailManagerExecutor のスコープは private です
     * 
     * @return executor
     */
    private ThreadPoolExecutor getThumbnailExecutor() {
        if (thumbnailManagerExecutor == null || thumbnailManagerExecutor.isShutdown()) {
            thumbnailManagerExecutor = new ThreadPoolExecutor(4, 10, 3600, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        }
        return thumbnailManagerExecutor;
    }

ThreadPoolExecutor のコンストラクターの引数について

  • corePoolSize アイドルであってもプール内に維持されるスレッドの数 => 4
  • maximumPoolSize プール内で可能なスレッドの最大数 => 10
  • keepAliveTime- スレッドの数がコアよりも多い場合、これは超過したアイドル状態のスレッドが新しいタスクを待機してから終了するまでの最大時間 => 3600
  • unit keepAliveTime 引数の時間単位
  • workQueue タスクが超過するまで保持するために使用するキュー。このキューは、execute メソッドで送信された Runnable タスクだけを保持する

ImageView にサムネイルをセットする

    /**
     * ImageView にサムネイルをセットする
     * 
     * @param icon
     *            ImageViewです
     * @param FileItem
     *            ファイル情報が入ったコンテナ
     */
    public void setThumbnailIntoView(final ImageView icon, final FileItem item) {
        // ★WeakReference を使いましょう
        final WeakReference<ImageView> iconHolder = new WeakReference<ImageView>(icon);
        final Resources res = icon.getResources();
        getThumbnailExecutor().execute(new Runnable() {
            public void run() {
                // デフォルトのサムネイルか何かを表示させる処理
                setThumbnail(iconHolder.get(), getDefaultIconResource(item));
                // ファイルのサムネイル(ドキュメントの縮小版画像とか)のキャッシュがあれば取得する処理
                Bitmap cachedIcon = getCachedIcon(item);
                // キャッシュがあったら、デフォルトのサムネイルから置き換える処理
                if (cachedIcon != null) {
                    setThumbnail(iconHolder.get(), new BitmapDrawable(res, cachedIcon));
                }
            }
        });

    }

さんこうしりょう

QiitaでもThreadPoolExecutor関連記事を書いている人がいました

7
9
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
7
9