1/*
2 * Copyright (C) 2014 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.systemui.qs;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.IntentFilter;
23import android.content.SharedPreferences;
24
25import com.android.systemui.R;
26import com.android.systemui.statusbar.policy.Listenable;
27
28public class UsageTracker implements Listenable {
29    private static final long MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
30
31    private final Context mContext;
32    private final long mTimeToShowTile;
33    private final String mPrefKey;
34    private final String mResetAction;
35
36    private boolean mRegistered;
37
38    public UsageTracker(Context context, Class<?> tile) {
39        mContext = context;
40        mPrefKey = tile.getSimpleName() + "LastUsed";
41        mTimeToShowTile = MILLIS_PER_DAY * mContext.getResources()
42                .getInteger(R.integer.days_to_show_timeout_tiles);
43        mResetAction = "com.android.systemui.qs." + tile.getSimpleName() + ".usage_reset";
44    }
45
46    @Override
47    public void setListening(boolean listen) {
48        if (listen && !mRegistered) {
49             mContext.registerReceiver(mReceiver, new IntentFilter(mResetAction));
50             mRegistered = true;
51        } else if (!listen && mRegistered) {
52            mContext.unregisterReceiver(mReceiver);
53            mRegistered = false;
54        }
55    }
56
57    public boolean isRecentlyUsed() {
58        long lastUsed = getSharedPrefs().getLong(mPrefKey, 0);
59        return (System.currentTimeMillis() - lastUsed) < mTimeToShowTile;
60    }
61
62    public void trackUsage() {
63        getSharedPrefs().edit().putLong(mPrefKey, System.currentTimeMillis()).commit();
64    }
65
66    public void reset() {
67        getSharedPrefs().edit().remove(mPrefKey).commit();
68    }
69
70    private SharedPreferences getSharedPrefs() {
71        return mContext.getSharedPreferences(mContext.getPackageName(), 0);
72    }
73
74    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
75        @Override
76        public void onReceive(Context context, Intent intent) {
77            if (mResetAction.equals(intent.getAction())) {
78                reset();
79            }
80        }
81    };
82}
83