1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.gallery3d.common;
18
19import android.os.AsyncTask;
20import android.os.Build;
21
22import java.lang.reflect.InvocationTargetException;
23import java.lang.reflect.Method;
24import java.util.concurrent.Executor;
25
26/**
27 * Helper class to execute an AsyncTask in parallel if SDK version is 11 or newer.
28 */
29public class AsyncTaskUtil {
30    private static Method sMethodExecuteOnExecutor;
31    private static Executor sExecutor;
32    static {
33        if (Build.VERSION.SDK_INT >= 11) {
34            try {
35                sExecutor = (Executor) AsyncTask.class.getField("THREAD_POOL_EXECUTOR")
36                        .get(null);
37                sMethodExecuteOnExecutor = AsyncTask.class.getMethod(
38                        "executeOnExecutor", Executor.class, Object[].class);
39            } catch (IllegalAccessException e) {
40                throw new RuntimeException(e);
41            } catch (NoSuchFieldException e) {
42                throw new RuntimeException(e);
43            } catch (NoSuchMethodException e) {
44                throw new RuntimeException(e);
45            }
46        }
47    }
48
49    public static <Param> void executeInParallel(AsyncTask<Param, ?, ?> task, Param... params) {
50        if (Build.VERSION.SDK_INT < 11) {
51            task.execute(params);
52        } else {
53            try {
54                sMethodExecuteOnExecutor.invoke(task, sExecutor, params);
55            } catch (IllegalAccessException e) {
56                throw new RuntimeException(e);
57            } catch (InvocationTargetException e) {
58                throw new RuntimeException(e);
59            }
60        }
61    }
62
63    private AsyncTaskUtil() {
64    }
65}
66
67