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 
17 package com.android.inputmethod.latin.utils;
18 
19 import android.content.Context;
20 import android.content.pm.PackageInfo;
21 import android.content.pm.PackageManager;
22 import android.os.AsyncTask;
23 import android.util.LruCache;
24 
25 import com.android.inputmethod.compat.AppWorkaroundsUtils;
26 
27 public final class TargetPackageInfoGetterTask extends
28         AsyncTask<String, Void, PackageInfo> {
29     private static final int MAX_CACHE_ENTRIES = 64; // arbitrary
30     private static final LruCache<String, PackageInfo> sCache = new LruCache<>(MAX_CACHE_ENTRIES);
31 
getCachedPackageInfo(final String packageName)32     public static PackageInfo getCachedPackageInfo(final String packageName) {
33         if (null == packageName) return null;
34         return sCache.get(packageName);
35     }
36 
removeCachedPackageInfo(final String packageName)37     public static void removeCachedPackageInfo(final String packageName) {
38         sCache.remove(packageName);
39     }
40 
41     private Context mContext;
42     private final AsyncResultHolder<AppWorkaroundsUtils> mResult;
43 
TargetPackageInfoGetterTask(final Context context, final AsyncResultHolder<AppWorkaroundsUtils> result)44     public TargetPackageInfoGetterTask(final Context context,
45             final AsyncResultHolder<AppWorkaroundsUtils> result) {
46         mContext = context;
47         mResult = result;
48     }
49 
50     @Override
doInBackground(final String... packageName)51     protected PackageInfo doInBackground(final String... packageName) {
52         final PackageManager pm = mContext.getPackageManager();
53         mContext = null; // Bazooka-powered anti-leak device
54         try {
55             final PackageInfo packageInfo = pm.getPackageInfo(packageName[0], 0 /* flags */);
56             sCache.put(packageName[0], packageInfo);
57             return packageInfo;
58         } catch (android.content.pm.PackageManager.NameNotFoundException e) {
59             return null;
60         }
61     }
62 
63     @Override
onPostExecute(final PackageInfo info)64     protected void onPostExecute(final PackageInfo info) {
65         mResult.set(new AppWorkaroundsUtils(info));
66     }
67 }
68