summaryrefslogtreecommitdiffstats
path: root/src/com/android/settings/applications/ProtectedAppsActivity.java
blob: a1c6cd5a232ab9ca072995c14b66cd14bec4df01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.applications;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.cyanogenmod.ProtectedAppsReceiver;

import cyanogenmod.providers.CMSettings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ProtectedAppsActivity extends Activity {
    private static final int REQ_ENTER_PATTERN = 1;
    private static final int REQ_RESET_PATTERN = 2;

    private static final String NEEDS_UNLOCK = "needs_unlock";

    private ListView mListView;

    private static final int MENU_RESET = 0;
    private static final int MENU_RESET_LOCK = 1;

    private PackageManager mPackageManager;

    private AppsAdapter mAppsAdapter;

    private ArrayList<ComponentName> mProtect;

    private boolean mWaitUserAuth = false;
    private boolean mUserIsAuth = false;
    private Intent mTargetIntent;

    private HashSet<ComponentName> mProtectedApps = new HashSet<ComponentName>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Handle incoming target activity
        Intent incomingIntent = getIntent();
        if (incomingIntent.hasExtra("com.android.settings.PROTECTED_APP_TARGET_INTENT")) {
            mTargetIntent =
                    incomingIntent.getParcelableExtra(
                            "com.android.settings.PROTECTED_APP_TARGET_INTENT");
        }

        setTitle(R.string.protected_apps);
        setContentView(R.layout.hidden_apps_list);

        mPackageManager = getPackageManager();
        mAppsAdapter = new AppsAdapter(this, R.layout.hidden_apps_list_item);
        mAppsAdapter.setNotifyOnChange(true);

        mListView = (ListView) findViewById(R.id.protected_apps_list);
        mListView.setAdapter(mAppsAdapter);

        mProtect = new ArrayList<ComponentName>();

        if (savedInstanceState != null) {
            mUserIsAuth = savedInstanceState.getBoolean(NEEDS_UNLOCK);
        }

        if (!mUserIsAuth) {
            // Require unlock
            Intent lockPattern = new Intent(this, LockPatternActivity.class);
            startActivityForResult(lockPattern, REQ_ENTER_PATTERN);
        } else {
            //LAUNCH
            if (mTargetIntent != null) {
                launchTargetActivityInfoAndFinish();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(NEEDS_UNLOCK, mUserIsAuth);
    }

    @Override
    protected void onResume() {
        super.onResume();

        AsyncTask<Void, Void, List<AppEntry>> refreshAppsTask =
                new AsyncTask<Void, Void, List<AppEntry>>() {

                    @Override
                    protected void onPostExecute(List<AppEntry> apps) {
                        mAppsAdapter.clear();
                        mAppsAdapter.addAll(apps);
                    }

                    @Override
                    protected List<AppEntry> doInBackground(Void... params) {
                        return refreshApps();
                    }
                };
        refreshAppsTask.execute(null, null, null);

        getActionBar().setDisplayHomeAsUpEnabled(true);

        // Update Protected Apps list
        updateProtectedComponentsList();
    }

    private void updateProtectedComponentsList() {
        String protectedComponents = CMSettings.Secure.getString(getContentResolver(),
                CMSettings.Secure.PROTECTED_COMPONENTS);
        protectedComponents = protectedComponents == null ? "" : protectedComponents;
        String [] flattened = protectedComponents.split("\\|");
        mProtectedApps = new HashSet<ComponentName>(flattened.length);
        for (String flat : flattened) {
            ComponentName cmp = ComponentName.unflattenFromString(flat);
            if (cmp != null) {
                mProtectedApps.add(cmp);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        // Don't stick around
        if (mWaitUserAuth && !mUserIsAuth) {
            finish();
        }
    }

    private boolean getProtectedStateFromComponentName(ComponentName componentName) {
        return mProtectedApps.contains(componentName);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQ_ENTER_PATTERN:
                mWaitUserAuth = true;
                switch (resultCode) {
                    case RESULT_OK:
                        //Nothing to do, proceed!
                        mUserIsAuth = true;
                        if (mTargetIntent != null) {
                            launchTargetActivityInfoAndFinish();
                        }
                        break;
                    case RESULT_CANCELED:
                        // user failed to define a pattern, do not lock the folder
                        finish();
                        break;
                }
                break;
            case REQ_RESET_PATTERN:
                mWaitUserAuth = true;
                mUserIsAuth = false;
        }
    }

    private void launchTargetActivityInfoAndFinish() {
        Intent launchIntent = mTargetIntent;
        startActivity(launchIntent);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_RESET, 0, R.string.menu_hidden_apps_delete)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        menu.add(0, MENU_RESET_LOCK, 0, R.string.menu_hidden_apps_reset_lock)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        return true;
    }

    private void reset() {
        ArrayList<ComponentName> componentsList = new ArrayList<ComponentName>();

        // Check to see if any components that have been protected that aren't present in
        // the ListView. This can happen if there are components which have been protected
        // but do not respond to the queryIntentActivities for Launcher Category
        ContentResolver resolver = getContentResolver();
        String hiddenComponents = CMSettings.Secure.getString(resolver,
                CMSettings.Secure.PROTECTED_COMPONENTS);

        if (hiddenComponents != null && !hiddenComponents.equals("")) {
            for (String flattened : hiddenComponents.split("\\|")) {
                ComponentName cmp = ComponentName.unflattenFromString(flattened);

                if (!componentsList.contains(cmp)) {
                    componentsList.add(cmp);
                }
            }
        }

        AppProtectList list = new AppProtectList(componentsList,
                PackageManager.COMPONENT_VISIBLE_STATUS);
        StoreComponentProtectedStatus task = new StoreComponentProtectedStatus(this);
        task.execute(list);
    }

    private void resetLock() {
        mWaitUserAuth = false;
        Intent lockPattern = new Intent(LockPatternActivity.RECREATE_PATTERN, null,
                this, LockPatternActivity.class);
        startActivityForResult(lockPattern, REQ_RESET_PATTERN);
    }

    private List<AppEntry> refreshApps() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> apps = mPackageManager.queryIntentActivities(mainIntent, 0);
        Collections.sort(apps, new ResolveInfo.DisplayNameComparator(mPackageManager));
        List<AppEntry> appEntries = new ArrayList<AppEntry>(apps.size());
        for (ResolveInfo info : apps) {
            appEntries.add(new AppEntry(info));
        }
        return appEntries;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_RESET:
                reset();
                return true;
            case MENU_RESET_LOCK:
                resetLock();
                return true;
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private final class AppEntry {
        public final ComponentName componentName;
        public final String title;

        public AppEntry(ResolveInfo info) {
            ActivityInfo aInfo = info.activityInfo;
            componentName = new ComponentName(aInfo.packageName, aInfo.name);
            title = info.loadLabel(mPackageManager).toString();
        }
    }

    private final class AppProtectList {
        public final ArrayList<ComponentName> componentNames;
        public final boolean state;

        public AppProtectList(ArrayList<ComponentName> componentNames, boolean state) {
            this.componentNames = new ArrayList<ComponentName>();
            for (ComponentName cn : componentNames) {
                this.componentNames.add(cn.clone());
            }

            this.state = state;
        }
    }

    public class StoreComponentProtectedStatus extends AsyncTask<AppProtectList, Void, Void> {
        private ProgressDialog mDialog;
        private Context mContext;

        public StoreComponentProtectedStatus(Context context) {
            mContext = context;
            mDialog = new ProgressDialog(mContext);
        }

        @Override
        protected void onPreExecute() {
            mDialog.setMessage(getResources().getString(R.string.saving_protected_components));
            mDialog.setCancelable(false);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (mDialog.isShowing()) {
                mDialog.dismiss();
            }

            mAppsAdapter.notifyDataSetChanged();
        }

        @Override
        protected Void doInBackground(final AppProtectList... args) {
            for (AppProtectList appList : args) {
                ProtectedAppsReceiver.updateProtectedAppComponentsAndNotify(mContext,
                        appList.componentNames, appList.state);
            }

            updateProtectedComponentsList();
            return null;
        }
    }

    /**
     * App view holder used to reuse the views inside the list.
     */
    private static class AppViewHolder {
        public final View container;
        public final TextView title;
        public final ImageView icon;
        public final View launch;
        public final CheckBox checkBox;

        public AppViewHolder(View parentView) {
            container = parentView.findViewById(R.id.app_item);
            icon = (ImageView) parentView.findViewById(R.id.icon);
            title = (TextView) parentView.findViewById(R.id.title);
            launch = parentView.findViewById(R.id.launch_app);
            checkBox = (CheckBox) parentView.findViewById(R.id.checkbox);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public class AppsAdapter extends ArrayAdapter<AppEntry> {

        private final LayoutInflater mInflator;

        private ConcurrentHashMap<String, Drawable> mIcons;
        private Drawable mDefaultImg;
        private List<AppEntry> mApps;

        public AppsAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);

            mApps = new ArrayList<AppEntry>();

            mInflator = LayoutInflater.from(context);

            // set the default icon till the actual app icon is loaded in async task
            mDefaultImg = context.getResources().getDrawable(android.R.mipmap.sym_def_app_icon);
            mIcons = new ConcurrentHashMap<String, Drawable>();
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            AppViewHolder viewHolder;

            if (convertView == null) {
                convertView = mInflator.inflate(R.layout.hidden_apps_list_item, parent, false);
                viewHolder = new AppViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (AppViewHolder) convertView.getTag();
            }

            AppEntry app = getItem(position);

            viewHolder.title.setText(app.title);

            Drawable icon = mIcons.get(app.componentName.getPackageName());
            viewHolder.icon.setImageDrawable(icon != null ? icon : mDefaultImg);

            boolean state = getProtectedStateFromComponentName(app.componentName);
            viewHolder.checkBox.setChecked(state);
            if (state) {
                viewHolder.launch.setVisibility(View.VISIBLE);
                viewHolder.launch.setTag(app);
                viewHolder.launch.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ComponentName cName = ((AppEntry)v.getTag()).componentName;
                        Intent intent = new Intent();
                        intent.setClassName(cName.getPackageName(), cName.getClassName());
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
            } else {
                viewHolder.launch.setVisibility(View.GONE);
            }

            viewHolder.container.setTag(position);
            viewHolder.container.setOnClickListener(mAppClickListener);
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            // If we have new items, we have to load their icons
            // If items were deleted, remove them from our mApps
            List<AppEntry> newApps = new ArrayList<AppEntry>(getCount());
            List<AppEntry> oldApps = new ArrayList<AppEntry>(getCount());
            for (int i = 0; i < getCount(); i++) {
                AppEntry app = getItem(i);
                if (mApps.contains(app)) {
                    oldApps.add(app);
                } else {
                    newApps.add(app);
                }
            }

            if (newApps.size() > 0) {
                new LoadIconsTask().execute(newApps.toArray(new AppEntry[] {}));
                newApps.addAll(oldApps);
                mApps = newApps;
            } else {
                mApps = oldApps;
            }
        }

        /**
         * An asynchronous task to load the icons of the installed applications.
         */
        private class LoadIconsTask extends AsyncTask<AppEntry, Void, Void> {
            @Override
            protected Void doInBackground(AppEntry... apps) {
                for (AppEntry app : apps) {
                    try {
                        String packageName = app.componentName.getPackageName();
                        if (mIcons.containsKey(packageName)) {
                            continue;
                        }
                        Drawable icon = mPackageManager.getApplicationIcon(packageName);
                        mIcons.put(packageName, icon);
                        publishProgress();
                    } catch (PackageManager.NameNotFoundException e) {
                        // ignored; app will show up with default image
                    }
                }

                return null;
            }

            @Override
            protected void onProgressUpdate(Void... progress) {
                notifyDataSetChanged();
            }
        }
    }

    private View.OnClickListener mAppClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            ComponentName cn = mAppsAdapter.getItem(position).componentName;
            ArrayList<ComponentName> componentsList = new ArrayList<ComponentName>();
            componentsList.add(cn);
            boolean state = getProtectedStateFromComponentName(cn);

            AppProtectList list = new AppProtectList(componentsList, state);
            StoreComponentProtectedStatus task =
                    new StoreComponentProtectedStatus(ProtectedAppsActivity.this);
            task.execute(list);
        }
    };
}