1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.latin;
18
19import android.content.Context;
20import android.content.pm.ApplicationInfo;
21import android.content.pm.PackageManager;
22import android.os.AsyncTask;
23import android.util.LruCache;
24
25public final class TargetApplicationGetter extends AsyncTask<String, Void, ApplicationInfo> {
26    private static final int MAX_CACHE_ENTRIES = 64; // arbitrary
27    private static LruCache<String, ApplicationInfo> sCache =
28            new LruCache<String, ApplicationInfo>(MAX_CACHE_ENTRIES);
29
30    public static ApplicationInfo getCachedApplicationInfo(final String packageName) {
31        if (null == packageName) return null;
32        return sCache.get(packageName);
33    }
34
35    public static void removeApplicationInfoCache(final String packageName) {
36        sCache.remove(packageName);
37    }
38
39    public interface OnTargetApplicationKnownListener {
40        public void onTargetApplicationKnown(final ApplicationInfo info);
41    }
42
43    private Context mContext;
44    private final OnTargetApplicationKnownListener mListener;
45
46    public TargetApplicationGetter(final Context context,
47            final OnTargetApplicationKnownListener listener) {
48        mContext = context;
49        mListener = listener;
50    }
51
52    @Override
53    protected ApplicationInfo doInBackground(final String... packageName) {
54        final PackageManager pm = mContext.getPackageManager();
55        mContext = null; // Bazooka-powered anti-leak device
56        try {
57            final ApplicationInfo targetAppInfo =
58                    pm.getApplicationInfo(packageName[0], 0 /* flags */);
59            sCache.put(packageName[0], targetAppInfo);
60            return targetAppInfo;
61        } catch (android.content.pm.PackageManager.NameNotFoundException e) {
62            return null;
63        }
64    }
65
66    @Override
67    protected void onPostExecute(final ApplicationInfo info) {
68        mListener.onTargetApplicationKnown(info);
69    }
70}
71