PackagesMonitor.java revision bb0be068e9182278d30efd42cad5cf369ff93db4
1/*
2 * Copyright (C) 2010 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.app;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.SharedPreferences;
23import android.preference.PreferenceManager;
24
25import com.android.gallery3d.picasasource.PicasaSource;
26
27public class PackagesMonitor extends BroadcastReceiver {
28    public static final String KEY_PACKAGES_VERSION  = "packages-version";
29
30    public synchronized static int getPackagesVersion(Context context) {
31        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
32        return prefs.getInt(KEY_PACKAGES_VERSION, 1);
33    }
34
35    @Override
36    public void onReceive(final Context context, final Intent intent) {
37        final PendingResult result = goAsync();
38        new Thread("GalleryPackagesMonitorAsync") {
39            @Override
40            public void run() {
41                try {
42                    onReceiveAsync(context, intent);
43                } catch (Throwable t) {
44                    Log.e("PackagesMonitor", "onReceiveAsync", t);
45                } finally {
46                    result.finish();
47                }
48            }
49        }.start();
50    }
51
52    // Runs in a background thread.
53    private void onReceiveAsync(Context context, Intent intent) {
54        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
55
56        int version = prefs.getInt(KEY_PACKAGES_VERSION, 1);
57        prefs.edit().putInt(KEY_PACKAGES_VERSION, version + 1).commit();
58
59        String action = intent.getAction();
60        String packageName = intent.getData().getSchemeSpecificPart();
61        if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
62            PicasaSource.onPackageAdded(context, packageName);
63        } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
64            PicasaSource.onPackageRemoved(context, packageName);
65        } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
66            PicasaSource.onPackageChanged(context, packageName);
67        }
68    }
69}
70