1 /*
2  * Copyright (C) 2008 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.internal.app;
18 
19 import android.app.Activity;
20 import android.app.ActivityThread;
21 import android.app.usage.UsageStats;
22 import android.app.usage.UsageStatsManager;
23 import android.os.AsyncTask;
24 import android.provider.Settings;
25 import android.text.TextUtils;
26 import android.util.Slog;
27 import android.widget.AbsListView;
28 import com.android.internal.R;
29 import com.android.internal.content.PackageMonitor;
30 
31 import android.app.ActivityManager;
32 import android.app.ActivityManagerNative;
33 import android.app.AppGlobals;
34 import android.content.ComponentName;
35 import android.content.Context;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.pm.ActivityInfo;
39 import android.content.pm.ApplicationInfo;
40 import android.content.pm.LabeledIntent;
41 import android.content.pm.PackageManager;
42 import android.content.pm.PackageManager.NameNotFoundException;
43 import android.content.pm.ResolveInfo;
44 import android.content.pm.UserInfo;
45 import android.content.res.Resources;
46 import android.graphics.drawable.Drawable;
47 import android.net.Uri;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.PatternMatcher;
51 import android.os.RemoteException;
52 import android.os.UserHandle;
53 import android.os.UserManager;
54 import android.util.Log;
55 import android.view.LayoutInflater;
56 import android.view.View;
57 import android.view.ViewGroup;
58 import android.widget.AdapterView;
59 import android.widget.BaseAdapter;
60 import android.widget.Button;
61 import android.widget.ImageView;
62 import android.widget.ListView;
63 import android.widget.TextView;
64 import android.widget.Toast;
65 import com.android.internal.widget.ResolverDrawerLayout;
66 
67 import java.text.Collator;
68 import java.util.ArrayList;
69 import java.util.Collections;
70 import java.util.Comparator;
71 import java.util.HashSet;
72 import java.util.Iterator;
73 import java.util.List;
74 import java.util.Map;
75 import java.util.Set;
76 
77 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
78 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
79 
80 /**
81  * This activity is displayed when the system attempts to start an Intent for
82  * which there is more than one matching activity, allowing the user to decide
83  * which to go to.  It is not normally used directly by application developers.
84  */
85 public class ResolverActivity extends Activity implements AdapterView.OnItemClickListener {
86     private static final String TAG = "ResolverActivity";
87     private static final boolean DEBUG = false;
88 
89     private int mLaunchedFromUid;
90     private ResolveListAdapter mAdapter;
91     private PackageManager mPm;
92     private boolean mSafeForwardingMode;
93     private boolean mAlwaysUseOption;
94     private boolean mShowExtended;
95     private ListView mListView;
96     private Button mAlwaysButton;
97     private Button mOnceButton;
98     private View mProfileView;
99     private int mIconDpi;
100     private int mIconSize;
101     private int mMaxColumns;
102     private int mLastSelected = ListView.INVALID_POSITION;
103     private boolean mResolvingHome = false;
104     private int mProfileSwitchMessageId = -1;
105     private Intent mIntent;
106 
107     private UsageStatsManager mUsm;
108     private Map<String, UsageStats> mStats;
109     private static final long USAGE_STATS_PERIOD = 1000 * 60 * 60 * 24 * 14;
110 
111     private boolean mRegistered;
112     private final PackageMonitor mPackageMonitor = new PackageMonitor() {
113         @Override public void onSomePackagesChanged() {
114             mAdapter.handlePackagesChanged();
115             if (mProfileView != null) {
116                 bindProfileView();
117             }
118         }
119     };
120 
121     private enum ActionTitle {
122         VIEW(Intent.ACTION_VIEW,
123                 com.android.internal.R.string.whichViewApplication,
124                 com.android.internal.R.string.whichViewApplicationNamed),
125         EDIT(Intent.ACTION_EDIT,
126                 com.android.internal.R.string.whichEditApplication,
127                 com.android.internal.R.string.whichEditApplicationNamed),
128         SEND(Intent.ACTION_SEND,
129                 com.android.internal.R.string.whichSendApplication,
130                 com.android.internal.R.string.whichSendApplicationNamed),
131         SENDTO(Intent.ACTION_SENDTO,
132                 com.android.internal.R.string.whichSendApplication,
133                 com.android.internal.R.string.whichSendApplicationNamed),
134         SEND_MULTIPLE(Intent.ACTION_SEND_MULTIPLE,
135                 com.android.internal.R.string.whichSendApplication,
136                 com.android.internal.R.string.whichSendApplicationNamed),
137         DEFAULT(null,
138                 com.android.internal.R.string.whichApplication,
139                 com.android.internal.R.string.whichApplicationNamed),
140         HOME(Intent.ACTION_MAIN,
141                 com.android.internal.R.string.whichHomeApplication,
142                 com.android.internal.R.string.whichHomeApplicationNamed);
143 
144         public final String action;
145         public final int titleRes;
146         public final int namedTitleRes;
147 
ActionTitle(String action, int titleRes, int namedTitleRes)148         ActionTitle(String action, int titleRes, int namedTitleRes) {
149             this.action = action;
150             this.titleRes = titleRes;
151             this.namedTitleRes = namedTitleRes;
152         }
153 
forAction(String action)154         public static ActionTitle forAction(String action) {
155             for (ActionTitle title : values()) {
156                 if (title != HOME && action != null && action.equals(title.action)) {
157                     return title;
158                 }
159             }
160             return DEFAULT;
161         }
162     }
163 
makeMyIntent()164     private Intent makeMyIntent() {
165         Intent intent = new Intent(getIntent());
166         intent.setComponent(null);
167         // The resolver activity is set to be hidden from recent tasks.
168         // we don't want this attribute to be propagated to the next activity
169         // being launched.  Note that if the original Intent also had this
170         // flag set, we are now losing it.  That should be a very rare case
171         // and we can live with this.
172         intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
173         return intent;
174     }
175 
176     @Override
onCreate(Bundle savedInstanceState)177     protected void onCreate(Bundle savedInstanceState) {
178         // Use a specialized prompt when we're handling the 'Home' app startActivity()
179         final Intent intent = makeMyIntent();
180         final Set<String> categories = intent.getCategories();
181         if (Intent.ACTION_MAIN.equals(intent.getAction())
182                 && categories != null
183                 && categories.size() == 1
184                 && categories.contains(Intent.CATEGORY_HOME)) {
185             // Note: this field is not set to true in the compatibility version.
186             mResolvingHome = true;
187         }
188 
189         setSafeForwardingMode(true);
190 
191         onCreate(savedInstanceState, intent, null, 0, null, null, true);
192     }
193 
194     /**
195      * Compatibility version for other bundled services that use this ocerload without
196      * a default title resource
197      */
onCreate(Bundle savedInstanceState, Intent intent, CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList, boolean alwaysUseOption)198     protected void onCreate(Bundle savedInstanceState, Intent intent,
199             CharSequence title, Intent[] initialIntents,
200             List<ResolveInfo> rList, boolean alwaysUseOption) {
201         onCreate(savedInstanceState, intent, title, 0, initialIntents, rList, alwaysUseOption);
202     }
203 
onCreate(Bundle savedInstanceState, Intent intent, CharSequence title, int defaultTitleRes, Intent[] initialIntents, List<ResolveInfo> rList, boolean alwaysUseOption)204     protected void onCreate(Bundle savedInstanceState, Intent intent,
205             CharSequence title, int defaultTitleRes, Intent[] initialIntents,
206             List<ResolveInfo> rList, boolean alwaysUseOption) {
207         setTheme(R.style.Theme_DeviceDefault_Resolver);
208         super.onCreate(savedInstanceState);
209 
210         // Determine whether we should show that intent is forwarded
211         // from managed profile to owner or other way around.
212         setProfileSwitchMessageId(intent.getContentUserHint());
213 
214         try {
215             mLaunchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid(
216                     getActivityToken());
217         } catch (RemoteException e) {
218             mLaunchedFromUid = -1;
219         }
220         mPm = getPackageManager();
221         mUsm = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
222 
223         final long sinceTime = System.currentTimeMillis() - USAGE_STATS_PERIOD;
224         mStats = mUsm.queryAndAggregateUsageStats(sinceTime, System.currentTimeMillis());
225 
226         mMaxColumns = getResources().getInteger(R.integer.config_maxResolverActivityColumns);
227 
228         mPackageMonitor.register(this, getMainLooper(), false);
229         mRegistered = true;
230 
231         final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
232         mIconDpi = am.getLauncherLargeIconDensity();
233         mIconSize = am.getLauncherLargeIconSize();
234 
235         mIntent = new Intent(intent);
236         mAdapter = new ResolveListAdapter(this, initialIntents, rList,
237                 mLaunchedFromUid, alwaysUseOption);
238 
239         final int layoutId;
240         final boolean useHeader;
241         if (mAdapter.hasFilteredItem()) {
242             layoutId = R.layout.resolver_list_with_default;
243             alwaysUseOption = false;
244             useHeader = true;
245         } else {
246             useHeader = false;
247             layoutId = R.layout.resolver_list;
248         }
249         mAlwaysUseOption = alwaysUseOption;
250 
251         if (mLaunchedFromUid < 0 || UserHandle.isIsolated(mLaunchedFromUid)) {
252             // Gulp!
253             finish();
254             return;
255         }
256 
257         int count = mAdapter.mList.size();
258         if (count > 1 || (count == 1 && mAdapter.getOtherProfile() != null)) {
259             setContentView(layoutId);
260             mListView = (ListView) findViewById(R.id.resolver_list);
261             mListView.setAdapter(mAdapter);
262             mListView.setOnItemClickListener(this);
263             mListView.setOnItemLongClickListener(new ItemLongClickListener());
264 
265             if (alwaysUseOption) {
266                 mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
267             }
268 
269             if (useHeader) {
270                 mListView.addHeaderView(LayoutInflater.from(this).inflate(
271                         R.layout.resolver_different_item_header, mListView, false));
272             }
273         } else if (count == 1) {
274             safelyStartActivity(mAdapter.intentForPosition(0, false));
275             mPackageMonitor.unregister();
276             mRegistered = false;
277             finish();
278             return;
279         } else {
280             setContentView(R.layout.resolver_list);
281 
282             final TextView empty = (TextView) findViewById(R.id.empty);
283             empty.setVisibility(View.VISIBLE);
284 
285             mListView = (ListView) findViewById(R.id.resolver_list);
286             mListView.setVisibility(View.GONE);
287         }
288         // Prevent the Resolver window from becoming the top fullscreen window and thus from taking
289         // control of the system bars.
290         getWindow().clearFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR);
291 
292         final ResolverDrawerLayout rdl = (ResolverDrawerLayout) findViewById(R.id.contentPanel);
293         if (rdl != null) {
294             rdl.setOnDismissedListener(new ResolverDrawerLayout.OnDismissedListener() {
295                 @Override
296                 public void onDismissed() {
297                     finish();
298                 }
299             });
300         }
301 
302         if (title == null) {
303             title = getTitleForAction(intent.getAction(), defaultTitleRes);
304         }
305         if (!TextUtils.isEmpty(title)) {
306             final TextView titleView = (TextView) findViewById(R.id.title);
307             if (titleView != null) {
308                 titleView.setText(title);
309             }
310             setTitle(title);
311         }
312 
313         final ImageView iconView = (ImageView) findViewById(R.id.icon);
314         final DisplayResolveInfo iconInfo = mAdapter.getFilteredItem();
315         if (iconView != null && iconInfo != null) {
316             new LoadIconIntoViewTask(iconView).execute(iconInfo);
317         }
318 
319         if (alwaysUseOption || mAdapter.hasFilteredItem()) {
320             final ViewGroup buttonLayout = (ViewGroup) findViewById(R.id.button_bar);
321             if (buttonLayout != null) {
322                 buttonLayout.setVisibility(View.VISIBLE);
323                 mAlwaysButton = (Button) buttonLayout.findViewById(R.id.button_always);
324                 mOnceButton = (Button) buttonLayout.findViewById(R.id.button_once);
325             } else {
326                 mAlwaysUseOption = false;
327             }
328         }
329 
330         if (mAdapter.hasFilteredItem()) {
331             setAlwaysButtonEnabled(true, mAdapter.getFilteredPosition(), false);
332             mOnceButton.setEnabled(true);
333         }
334 
335         mProfileView = findViewById(R.id.profile_button);
336         if (mProfileView != null) {
337             mProfileView.setOnClickListener(new View.OnClickListener() {
338                 @Override
339                 public void onClick(View v) {
340                     final DisplayResolveInfo dri = mAdapter.getOtherProfile();
341                     if (dri == null) {
342                         return;
343                     }
344 
345                     final Intent intent = intentForDisplayResolveInfo(dri);
346                     onIntentSelected(dri.ri, intent, false);
347                     finish();
348                 }
349             });
350             bindProfileView();
351         }
352     }
353 
bindProfileView()354     void bindProfileView() {
355         final DisplayResolveInfo dri = mAdapter.getOtherProfile();
356         if (dri != null) {
357             mProfileView.setVisibility(View.VISIBLE);
358             final ImageView icon = (ImageView) mProfileView.findViewById(R.id.icon);
359             final TextView text = (TextView) mProfileView.findViewById(R.id.text1);
360             if (dri.displayIcon == null) {
361                 new LoadIconTask().execute(dri);
362             }
363             icon.setImageDrawable(dri.displayIcon);
364             text.setText(dri.displayLabel);
365         } else {
366             mProfileView.setVisibility(View.GONE);
367         }
368     }
369 
setProfileSwitchMessageId(int contentUserHint)370     private void setProfileSwitchMessageId(int contentUserHint) {
371         if (contentUserHint != UserHandle.USER_CURRENT &&
372                 contentUserHint != UserHandle.myUserId()) {
373             UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
374             UserInfo originUserInfo = userManager.getUserInfo(contentUserHint);
375             boolean originIsManaged = originUserInfo != null ? originUserInfo.isManagedProfile()
376                     : false;
377             boolean targetIsManaged = userManager.isManagedProfile();
378             if (originIsManaged && !targetIsManaged) {
379                 mProfileSwitchMessageId = com.android.internal.R.string.forward_intent_to_owner;
380             } else if (!originIsManaged && targetIsManaged) {
381                 mProfileSwitchMessageId = com.android.internal.R.string.forward_intent_to_work;
382             }
383         }
384     }
385 
386     /**
387      * Turn on launch mode that is safe to use when forwarding intents received from
388      * applications and running in system processes.  This mode uses Activity.startActivityAsCaller
389      * instead of the normal Activity.startActivity for launching the activity selected
390      * by the user.
391      *
392      * <p>This mode is set to true by default if the activity is initialized through
393      * {@link #onCreate(android.os.Bundle)}.  If a subclass calls one of the other onCreate
394      * methods, it is set to false by default.  You must set it before calling one of the
395      * more detailed onCreate methods, so that it will be set correctly in the case where
396      * there is only one intent to resolve and it is thus started immediately.</p>
397      */
setSafeForwardingMode(boolean safeForwarding)398     public void setSafeForwardingMode(boolean safeForwarding) {
399         mSafeForwardingMode = safeForwarding;
400     }
401 
getTitleForAction(String action, int defaultTitleRes)402     protected CharSequence getTitleForAction(String action, int defaultTitleRes) {
403         final ActionTitle title = mResolvingHome ? ActionTitle.HOME : ActionTitle.forAction(action);
404         final boolean named = mAdapter.hasFilteredItem();
405         if (title == ActionTitle.DEFAULT && defaultTitleRes != 0) {
406             return getString(defaultTitleRes);
407         } else {
408             return named ? getString(title.namedTitleRes, mAdapter.getFilteredItem().displayLabel) :
409                     getString(title.titleRes);
410         }
411     }
412 
dismiss()413     void dismiss() {
414         if (!isFinishing()) {
415             finish();
416         }
417     }
418 
getIcon(Resources res, int resId)419     Drawable getIcon(Resources res, int resId) {
420         Drawable result;
421         try {
422             result = res.getDrawableForDensity(resId, mIconDpi);
423         } catch (Resources.NotFoundException e) {
424             result = null;
425         }
426 
427         return result;
428     }
429 
loadIconForResolveInfo(ResolveInfo ri)430     Drawable loadIconForResolveInfo(ResolveInfo ri) {
431         Drawable dr;
432         try {
433             if (ri.resolvePackageName != null && ri.icon != 0) {
434                 dr = getIcon(mPm.getResourcesForApplication(ri.resolvePackageName), ri.icon);
435                 if (dr != null) {
436                     return dr;
437                 }
438             }
439             final int iconRes = ri.getIconResource();
440             if (iconRes != 0) {
441                 dr = getIcon(mPm.getResourcesForApplication(ri.activityInfo.packageName), iconRes);
442                 if (dr != null) {
443                     return dr;
444                 }
445             }
446         } catch (NameNotFoundException e) {
447             Log.e(TAG, "Couldn't find resources for package", e);
448         }
449         return ri.loadIcon(mPm);
450     }
451 
452     @Override
onRestart()453     protected void onRestart() {
454         super.onRestart();
455         if (!mRegistered) {
456             mPackageMonitor.register(this, getMainLooper(), false);
457             mRegistered = true;
458         }
459         mAdapter.handlePackagesChanged();
460         if (mProfileView != null) {
461             bindProfileView();
462         }
463     }
464 
465     @Override
onStop()466     protected void onStop() {
467         super.onStop();
468         if (mRegistered) {
469             mPackageMonitor.unregister();
470             mRegistered = false;
471         }
472         if ((getIntent().getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
473             // This resolver is in the unusual situation where it has been
474             // launched at the top of a new task.  We don't let it be added
475             // to the recent tasks shown to the user, and we need to make sure
476             // that each time we are launched we get the correct launching
477             // uid (not re-using the same resolver from an old launching uid),
478             // so we will now finish ourself since being no longer visible,
479             // the user probably can't get back to us.
480             if (!isChangingConfigurations()) {
481                 finish();
482             }
483         }
484     }
485 
486     @Override
onRestoreInstanceState(Bundle savedInstanceState)487     protected void onRestoreInstanceState(Bundle savedInstanceState) {
488         super.onRestoreInstanceState(savedInstanceState);
489         if (mAlwaysUseOption) {
490             final int checkedPos = mListView.getCheckedItemPosition();
491             final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
492             mLastSelected = checkedPos;
493             setAlwaysButtonEnabled(hasValidSelection, checkedPos, true);
494             mOnceButton.setEnabled(hasValidSelection);
495             if (hasValidSelection) {
496                 mListView.setSelection(checkedPos);
497             }
498         }
499     }
500 
501     @Override
onItemClick(AdapterView<?> parent, View view, int position, long id)502     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
503         position -= mListView.getHeaderViewsCount();
504         if (position < 0) {
505             // Header views don't count.
506             return;
507         }
508         ResolveInfo resolveInfo = mAdapter.resolveInfoForPosition(position, true);
509         if (mResolvingHome && hasManagedProfile()
510                 && !supportsManagedProfiles(resolveInfo)) {
511             Toast.makeText(this, String.format(getResources().getString(
512                     com.android.internal.R.string.activity_resolver_work_profiles_support),
513                     resolveInfo.activityInfo.loadLabel(getPackageManager()).toString()),
514                     Toast.LENGTH_LONG).show();
515             return;
516         }
517         final int checkedPos = mListView.getCheckedItemPosition();
518         final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
519         if (mAlwaysUseOption && (!hasValidSelection || mLastSelected != checkedPos)) {
520             setAlwaysButtonEnabled(hasValidSelection, checkedPos, true);
521             mOnceButton.setEnabled(hasValidSelection);
522             if (hasValidSelection) {
523                 mListView.smoothScrollToPosition(checkedPos);
524             }
525             mLastSelected = checkedPos;
526         } else {
527             startSelected(position, false, true);
528         }
529     }
530 
hasManagedProfile()531     private boolean hasManagedProfile() {
532         UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
533         if (userManager == null) {
534             return false;
535         }
536 
537         try {
538             List<UserInfo> profiles = userManager.getProfiles(getUserId());
539             for (UserInfo userInfo : profiles) {
540                 if (userInfo != null && userInfo.isManagedProfile()) {
541                     return true;
542                 }
543             }
544         } catch (SecurityException e) {
545             return false;
546         }
547         return false;
548     }
549 
supportsManagedProfiles(ResolveInfo resolveInfo)550     private boolean supportsManagedProfiles(ResolveInfo resolveInfo) {
551         try {
552             ApplicationInfo appInfo = getPackageManager().getApplicationInfo(
553                     resolveInfo.activityInfo.packageName, 0 /* default flags */);
554             return versionNumberAtLeastL(appInfo.targetSdkVersion);
555         } catch (NameNotFoundException e) {
556             return false;
557         }
558     }
559 
versionNumberAtLeastL(int versionNumber)560     private boolean versionNumberAtLeastL(int versionNumber) {
561         return versionNumber >= Build.VERSION_CODES.LOLLIPOP;
562     }
563 
setAlwaysButtonEnabled(boolean hasValidSelection, int checkedPos, boolean filtered)564     private void setAlwaysButtonEnabled(boolean hasValidSelection, int checkedPos,
565             boolean filtered) {
566         boolean enabled = false;
567         if (hasValidSelection) {
568             ResolveInfo ri = mAdapter.resolveInfoForPosition(checkedPos, filtered);
569             if (ri.targetUserId == UserHandle.USER_CURRENT) {
570                 enabled = true;
571             }
572         }
573         mAlwaysButton.setEnabled(enabled);
574     }
575 
onButtonClick(View v)576     public void onButtonClick(View v) {
577         final int id = v.getId();
578         startSelected(mAlwaysUseOption ?
579                 mListView.getCheckedItemPosition() : mAdapter.getFilteredPosition(),
580                 id == R.id.button_always,
581                 mAlwaysUseOption);
582         dismiss();
583     }
584 
startSelected(int which, boolean always, boolean filtered)585     void startSelected(int which, boolean always, boolean filtered) {
586         if (isFinishing()) {
587             return;
588         }
589         ResolveInfo ri = mAdapter.resolveInfoForPosition(which, filtered);
590         Intent intent = mAdapter.intentForPosition(which, filtered);
591         onIntentSelected(ri, intent, always);
592         finish();
593     }
594 
595     /**
596      * Replace me in subclasses!
597      */
getReplacementIntent(ActivityInfo aInfo, Intent defIntent)598     public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
599         return defIntent;
600     }
601 
onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck)602     protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
603         if ((mAlwaysUseOption || mAdapter.hasFilteredItem()) && mAdapter.mOrigResolveList != null) {
604             // Build a reasonable intent filter, based on what matched.
605             IntentFilter filter = new IntentFilter();
606 
607             if (intent.getAction() != null) {
608                 filter.addAction(intent.getAction());
609             }
610             Set<String> categories = intent.getCategories();
611             if (categories != null) {
612                 for (String cat : categories) {
613                     filter.addCategory(cat);
614                 }
615             }
616             filter.addCategory(Intent.CATEGORY_DEFAULT);
617 
618             int cat = ri.match&IntentFilter.MATCH_CATEGORY_MASK;
619             Uri data = intent.getData();
620             if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
621                 String mimeType = intent.resolveType(this);
622                 if (mimeType != null) {
623                     try {
624                         filter.addDataType(mimeType);
625                     } catch (IntentFilter.MalformedMimeTypeException e) {
626                         Log.w("ResolverActivity", e);
627                         filter = null;
628                     }
629                 }
630             }
631             if (data != null && data.getScheme() != null) {
632                 // We need the data specification if there was no type,
633                 // OR if the scheme is not one of our magical "file:"
634                 // or "content:" schemes (see IntentFilter for the reason).
635                 if (cat != IntentFilter.MATCH_CATEGORY_TYPE
636                         || (!"file".equals(data.getScheme())
637                                 && !"content".equals(data.getScheme()))) {
638                     filter.addDataScheme(data.getScheme());
639 
640                     // Look through the resolved filter to determine which part
641                     // of it matched the original Intent.
642                     Iterator<PatternMatcher> pIt = ri.filter.schemeSpecificPartsIterator();
643                     if (pIt != null) {
644                         String ssp = data.getSchemeSpecificPart();
645                         while (ssp != null && pIt.hasNext()) {
646                             PatternMatcher p = pIt.next();
647                             if (p.match(ssp)) {
648                                 filter.addDataSchemeSpecificPart(p.getPath(), p.getType());
649                                 break;
650                             }
651                         }
652                     }
653                     Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
654                     if (aIt != null) {
655                         while (aIt.hasNext()) {
656                             IntentFilter.AuthorityEntry a = aIt.next();
657                             if (a.match(data) >= 0) {
658                                 int port = a.getPort();
659                                 filter.addDataAuthority(a.getHost(),
660                                         port >= 0 ? Integer.toString(port) : null);
661                                 break;
662                             }
663                         }
664                     }
665                     pIt = ri.filter.pathsIterator();
666                     if (pIt != null) {
667                         String path = data.getPath();
668                         while (path != null && pIt.hasNext()) {
669                             PatternMatcher p = pIt.next();
670                             if (p.match(path)) {
671                                 filter.addDataPath(p.getPath(), p.getType());
672                                 break;
673                             }
674                         }
675                     }
676                 }
677             }
678 
679             if (filter != null) {
680                 final int N = mAdapter.mOrigResolveList.size();
681                 ComponentName[] set = new ComponentName[N];
682                 int bestMatch = 0;
683                 for (int i=0; i<N; i++) {
684                     ResolveInfo r = mAdapter.mOrigResolveList.get(i);
685                     set[i] = new ComponentName(r.activityInfo.packageName,
686                             r.activityInfo.name);
687                     if (r.match > bestMatch) bestMatch = r.match;
688                 }
689                 if (alwaysCheck) {
690                     getPackageManager().addPreferredActivity(filter, bestMatch, set,
691                             intent.getComponent());
692                 } else {
693                     try {
694                         AppGlobals.getPackageManager().setLastChosenActivity(intent,
695                                 intent.resolveTypeIfNeeded(getContentResolver()),
696                                 PackageManager.MATCH_DEFAULT_ONLY,
697                                 filter, bestMatch, intent.getComponent());
698                     } catch (RemoteException re) {
699                         Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
700                     }
701                 }
702             }
703         }
704 
705         if (intent != null) {
706             safelyStartActivity(intent);
707         }
708     }
709 
safelyStartActivity(Intent intent)710     public void safelyStartActivity(Intent intent) {
711         // If needed, show that intent is forwarded
712         // from managed profile to owner or other way around.
713         if (mProfileSwitchMessageId != -1) {
714             Toast.makeText(this, getString(mProfileSwitchMessageId), Toast.LENGTH_LONG).show();
715         }
716         if (!mSafeForwardingMode) {
717             startActivity(intent);
718             onActivityStarted(intent);
719             return;
720         }
721         try {
722             startActivityAsCaller(intent, null, UserHandle.USER_NULL);
723             onActivityStarted(intent);
724         } catch (RuntimeException e) {
725             String launchedFromPackage;
726             try {
727                 launchedFromPackage = ActivityManagerNative.getDefault().getLaunchedFromPackage(
728                         getActivityToken());
729             } catch (RemoteException e2) {
730                 launchedFromPackage = "??";
731             }
732             Slog.wtf(TAG, "Unable to launch as uid " + mLaunchedFromUid
733                     + " package " + launchedFromPackage + ", while running in "
734                     + ActivityThread.currentProcessName(), e);
735         }
736     }
737 
onActivityStarted(Intent intent)738     public void onActivityStarted(Intent intent) {
739         // Do nothing
740     }
741 
showAppDetails(ResolveInfo ri)742     void showAppDetails(ResolveInfo ri) {
743         Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
744                 .setData(Uri.fromParts("package", ri.activityInfo.packageName, null))
745                 .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
746         startActivity(in);
747     }
748 
intentForDisplayResolveInfo(DisplayResolveInfo dri)749     Intent intentForDisplayResolveInfo(DisplayResolveInfo dri) {
750         Intent intent = new Intent(dri.origIntent != null ? dri.origIntent :
751                 getReplacementIntent(dri.ri.activityInfo, mIntent));
752         intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
753                 |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
754         ActivityInfo ai = dri.ri.activityInfo;
755         intent.setComponent(new ComponentName(
756                 ai.applicationInfo.packageName, ai.name));
757         return intent;
758     }
759 
760     private final class DisplayResolveInfo {
761         ResolveInfo ri;
762         CharSequence displayLabel;
763         Drawable displayIcon;
764         CharSequence extendedInfo;
765         Intent origIntent;
766 
DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel, CharSequence pInfo, Intent pOrigIntent)767         DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
768                 CharSequence pInfo, Intent pOrigIntent) {
769             ri = pri;
770             displayLabel = pLabel;
771             extendedInfo = pInfo;
772             origIntent = pOrigIntent;
773         }
774     }
775 
776     private final class ResolveListAdapter extends BaseAdapter {
777         private final Intent[] mInitialIntents;
778         private final List<ResolveInfo> mBaseResolveList;
779         private ResolveInfo mLastChosen;
780         private DisplayResolveInfo mOtherProfile;
781         private final int mLaunchedFromUid;
782         private final LayoutInflater mInflater;
783 
784         List<DisplayResolveInfo> mList;
785         List<ResolveInfo> mOrigResolveList;
786 
787         private int mLastChosenPosition = -1;
788         private boolean mFilterLastUsed;
789 
ResolveListAdapter(Context context, Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid, boolean filterLastUsed)790         public ResolveListAdapter(Context context, Intent[] initialIntents,
791                 List<ResolveInfo> rList, int launchedFromUid, boolean filterLastUsed) {
792             mInitialIntents = initialIntents;
793             mBaseResolveList = rList;
794             mLaunchedFromUid = launchedFromUid;
795             mInflater = LayoutInflater.from(context);
796             mList = new ArrayList<DisplayResolveInfo>();
797             mFilterLastUsed = filterLastUsed;
798             rebuildList();
799         }
800 
handlePackagesChanged()801         public void handlePackagesChanged() {
802             rebuildList();
803             notifyDataSetChanged();
804             if (getCount() == 0) {
805                 // We no longer have any items...  just finish the activity.
806                 finish();
807             }
808         }
809 
getFilteredItem()810         public DisplayResolveInfo getFilteredItem() {
811             if (mFilterLastUsed && mLastChosenPosition >= 0) {
812                 // Not using getItem since it offsets to dodge this position for the list
813                 return mList.get(mLastChosenPosition);
814             }
815             return null;
816         }
817 
getOtherProfile()818         public DisplayResolveInfo getOtherProfile() {
819             return mOtherProfile;
820         }
821 
getFilteredPosition()822         public int getFilteredPosition() {
823             if (mFilterLastUsed && mLastChosenPosition >= 0) {
824                 return mLastChosenPosition;
825             }
826             return AbsListView.INVALID_POSITION;
827         }
828 
hasFilteredItem()829         public boolean hasFilteredItem() {
830             return mFilterLastUsed && mLastChosenPosition >= 0;
831         }
832 
rebuildList()833         private void rebuildList() {
834             List<ResolveInfo> currentResolveList;
835 
836             try {
837                 mLastChosen = AppGlobals.getPackageManager().getLastChosenActivity(
838                         mIntent, mIntent.resolveTypeIfNeeded(getContentResolver()),
839                         PackageManager.MATCH_DEFAULT_ONLY);
840             } catch (RemoteException re) {
841                 Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
842             }
843 
844             mList.clear();
845             if (mBaseResolveList != null) {
846                 currentResolveList = mOrigResolveList = mBaseResolveList;
847             } else {
848                 currentResolveList = mOrigResolveList = mPm.queryIntentActivities(
849                         mIntent, PackageManager.MATCH_DEFAULT_ONLY
850                         | (mFilterLastUsed ? PackageManager.GET_RESOLVED_FILTER : 0));
851                 // Filter out any activities that the launched uid does not
852                 // have permission for.  We don't do this when we have an explicit
853                 // list of resolved activities, because that only happens when
854                 // we are being subclassed, so we can safely launch whatever
855                 // they gave us.
856                 if (currentResolveList != null) {
857                     for (int i=currentResolveList.size()-1; i >= 0; i--) {
858                         ActivityInfo ai = currentResolveList.get(i).activityInfo;
859                         int granted = ActivityManager.checkComponentPermission(
860                                 ai.permission, mLaunchedFromUid,
861                                 ai.applicationInfo.uid, ai.exported);
862                         if (granted != PackageManager.PERMISSION_GRANTED) {
863                             // Access not allowed!
864                             if (mOrigResolveList == currentResolveList) {
865                                 mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList);
866                             }
867                             currentResolveList.remove(i);
868                         }
869                     }
870                 }
871             }
872             int N;
873             if ((currentResolveList != null) && ((N = currentResolveList.size()) > 0)) {
874                 // Only display the first matches that are either of equal
875                 // priority or have asked to be default options.
876                 ResolveInfo r0 = currentResolveList.get(0);
877                 for (int i=1; i<N; i++) {
878                     ResolveInfo ri = currentResolveList.get(i);
879                     if (DEBUG) Log.v(
880                         TAG,
881                         r0.activityInfo.name + "=" +
882                         r0.priority + "/" + r0.isDefault + " vs " +
883                         ri.activityInfo.name + "=" +
884                         ri.priority + "/" + ri.isDefault);
885                     if (r0.priority != ri.priority ||
886                         r0.isDefault != ri.isDefault) {
887                         while (i < N) {
888                             if (mOrigResolveList == currentResolveList) {
889                                 mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList);
890                             }
891                             currentResolveList.remove(i);
892                             N--;
893                         }
894                     }
895                 }
896                 if (N > 1) {
897                     Comparator<ResolveInfo> rComparator =
898                             new ResolverComparator(ResolverActivity.this, mIntent);
899                     Collections.sort(currentResolveList, rComparator);
900                 }
901                 // First put the initial items at the top.
902                 if (mInitialIntents != null) {
903                     for (int i=0; i<mInitialIntents.length; i++) {
904                         Intent ii = mInitialIntents[i];
905                         if (ii == null) {
906                             continue;
907                         }
908                         ActivityInfo ai = ii.resolveActivityInfo(
909                                 getPackageManager(), 0);
910                         if (ai == null) {
911                             Log.w(TAG, "No activity found for " + ii);
912                             continue;
913                         }
914                         ResolveInfo ri = new ResolveInfo();
915                         ri.activityInfo = ai;
916                         UserManager userManager =
917                                 (UserManager) getSystemService(Context.USER_SERVICE);
918                         if (userManager.isManagedProfile()) {
919                             ri.noResourceId = true;
920                         }
921                         if (ii instanceof LabeledIntent) {
922                             LabeledIntent li = (LabeledIntent)ii;
923                             ri.resolvePackageName = li.getSourcePackage();
924                             ri.labelRes = li.getLabelResource();
925                             ri.nonLocalizedLabel = li.getNonLocalizedLabel();
926                             ri.icon = li.getIconResource();
927                         }
928                         addResolveInfo(new DisplayResolveInfo(ri,
929                                 ri.loadLabel(getPackageManager()), null, ii));
930                     }
931                 }
932 
933                 // Check for applications with same name and use application name or
934                 // package name if necessary
935                 r0 = currentResolveList.get(0);
936                 int start = 0;
937                 CharSequence r0Label =  r0.loadLabel(mPm);
938                 mShowExtended = false;
939                 for (int i = 1; i < N; i++) {
940                     if (r0Label == null) {
941                         r0Label = r0.activityInfo.packageName;
942                     }
943                     ResolveInfo ri = currentResolveList.get(i);
944                     CharSequence riLabel = ri.loadLabel(mPm);
945                     if (riLabel == null) {
946                         riLabel = ri.activityInfo.packageName;
947                     }
948                     if (riLabel.equals(r0Label)) {
949                         continue;
950                     }
951                     processGroup(currentResolveList, start, (i-1), r0, r0Label);
952                     r0 = ri;
953                     r0Label = riLabel;
954                     start = i;
955                 }
956                 // Process last group
957                 processGroup(currentResolveList, start, (N-1), r0, r0Label);
958             }
959 
960             // Layout doesn't handle both profile button and last chosen
961             // so disable last chosen if profile button is present.
962             if (mOtherProfile != null && mLastChosenPosition >= 0) {
963                 mLastChosenPosition = -1;
964                 mFilterLastUsed = false;
965             }
966         }
967 
processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro, CharSequence roLabel)968         private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
969                 CharSequence roLabel) {
970             // Process labels from start to i
971             int num = end - start+1;
972             if (num == 1) {
973                 // No duplicate labels. Use label for entry at start
974                 addResolveInfo(new DisplayResolveInfo(ro, roLabel, null, null));
975                 updateLastChosenPosition(ro);
976             } else {
977                 mShowExtended = true;
978                 boolean usePkg = false;
979                 CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
980                 if (startApp == null) {
981                     usePkg = true;
982                 }
983                 if (!usePkg) {
984                     // Use HashSet to track duplicates
985                     HashSet<CharSequence> duplicates =
986                         new HashSet<CharSequence>();
987                     duplicates.add(startApp);
988                     for (int j = start+1; j <= end ; j++) {
989                         ResolveInfo jRi = rList.get(j);
990                         CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
991                         if ( (jApp == null) || (duplicates.contains(jApp))) {
992                             usePkg = true;
993                             break;
994                         } else {
995                             duplicates.add(jApp);
996                         }
997                     }
998                     // Clear HashSet for later use
999                     duplicates.clear();
1000                 }
1001                 for (int k = start; k <= end; k++) {
1002                     ResolveInfo add = rList.get(k);
1003                     if (usePkg) {
1004                         // Use application name for all entries from start to end-1
1005                         addResolveInfo(new DisplayResolveInfo(add, roLabel,
1006                                 add.activityInfo.packageName, null));
1007                     } else {
1008                         // Use package name for all entries from start to end-1
1009                         addResolveInfo(new DisplayResolveInfo(add, roLabel,
1010                                 add.activityInfo.applicationInfo.loadLabel(mPm), null));
1011                     }
1012                     updateLastChosenPosition(add);
1013                 }
1014             }
1015         }
1016 
updateLastChosenPosition(ResolveInfo info)1017         private void updateLastChosenPosition(ResolveInfo info) {
1018             if (mLastChosen != null
1019                     && mLastChosen.activityInfo.packageName.equals(info.activityInfo.packageName)
1020                     && mLastChosen.activityInfo.name.equals(info.activityInfo.name)) {
1021                 mLastChosenPosition = mList.size() - 1;
1022             }
1023         }
1024 
addResolveInfo(DisplayResolveInfo dri)1025         private void addResolveInfo(DisplayResolveInfo dri) {
1026             if (dri.ri.targetUserId != UserHandle.USER_CURRENT && mOtherProfile == null) {
1027                 // So far we only support a single other profile at a time.
1028                 // The first one we see gets special treatment.
1029                 mOtherProfile = dri;
1030             } else {
1031                 mList.add(dri);
1032             }
1033         }
1034 
resolveInfoForPosition(int position, boolean filtered)1035         public ResolveInfo resolveInfoForPosition(int position, boolean filtered) {
1036             return (filtered ? getItem(position) : mList.get(position)).ri;
1037         }
1038 
intentForPosition(int position, boolean filtered)1039         public Intent intentForPosition(int position, boolean filtered) {
1040             DisplayResolveInfo dri = filtered ? getItem(position) : mList.get(position);
1041             return intentForDisplayResolveInfo(dri);
1042         }
1043 
getCount()1044         public int getCount() {
1045             int result = mList.size();
1046             if (mFilterLastUsed && mLastChosenPosition >= 0) {
1047                 result--;
1048             }
1049             return result;
1050         }
1051 
getItem(int position)1052         public DisplayResolveInfo getItem(int position) {
1053             if (mFilterLastUsed && mLastChosenPosition >= 0 && position >= mLastChosenPosition) {
1054                 position++;
1055             }
1056             return mList.get(position);
1057         }
1058 
getItemId(int position)1059         public long getItemId(int position) {
1060             return position;
1061         }
1062 
getView(int position, View convertView, ViewGroup parent)1063         public View getView(int position, View convertView, ViewGroup parent) {
1064             View view = convertView;
1065             if (view == null) {
1066                 view = mInflater.inflate(
1067                         com.android.internal.R.layout.resolve_list_item, parent, false);
1068 
1069                 final ViewHolder holder = new ViewHolder(view);
1070                 view.setTag(holder);
1071             }
1072             bindView(view, getItem(position));
1073             return view;
1074         }
1075 
bindView(View view, DisplayResolveInfo info)1076         private final void bindView(View view, DisplayResolveInfo info) {
1077             final ViewHolder holder = (ViewHolder) view.getTag();
1078             holder.text.setText(info.displayLabel);
1079             if (mShowExtended) {
1080                 holder.text2.setVisibility(View.VISIBLE);
1081                 holder.text2.setText(info.extendedInfo);
1082             } else {
1083                 holder.text2.setVisibility(View.GONE);
1084             }
1085             if (info.displayIcon == null) {
1086                 new LoadIconTask().execute(info);
1087             }
1088             holder.icon.setImageDrawable(info.displayIcon);
1089         }
1090     }
1091 
1092     static class ViewHolder {
1093         public TextView text;
1094         public TextView text2;
1095         public ImageView icon;
1096 
ViewHolder(View view)1097         public ViewHolder(View view) {
1098             text = (TextView) view.findViewById(com.android.internal.R.id.text1);
1099             text2 = (TextView) view.findViewById(com.android.internal.R.id.text2);
1100             icon = (ImageView) view.findViewById(R.id.icon);
1101         }
1102     }
1103 
1104     class ItemLongClickListener implements AdapterView.OnItemLongClickListener {
1105 
1106         @Override
onItemLongClick(AdapterView<?> parent, View view, int position, long id)1107         public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
1108             position -= mListView.getHeaderViewsCount();
1109             if (position < 0) {
1110                 // Header views don't count.
1111                 return false;
1112             }
1113             ResolveInfo ri = mAdapter.resolveInfoForPosition(position, true);
1114             showAppDetails(ri);
1115             return true;
1116         }
1117 
1118     }
1119 
1120     class LoadIconTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
1121         @Override
doInBackground(DisplayResolveInfo... params)1122         protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
1123             final DisplayResolveInfo info = params[0];
1124             if (info.displayIcon == null) {
1125                 info.displayIcon = loadIconForResolveInfo(info.ri);
1126             }
1127             return info;
1128         }
1129 
1130         @Override
onPostExecute(DisplayResolveInfo info)1131         protected void onPostExecute(DisplayResolveInfo info) {
1132             if (mProfileView != null && mAdapter.getOtherProfile() == info) {
1133                 bindProfileView();
1134             }
1135             mAdapter.notifyDataSetChanged();
1136         }
1137     }
1138 
1139     class LoadIconIntoViewTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
1140         final ImageView mTargetView;
1141 
LoadIconIntoViewTask(ImageView target)1142         public LoadIconIntoViewTask(ImageView target) {
1143             mTargetView = target;
1144         }
1145 
1146         @Override
doInBackground(DisplayResolveInfo... params)1147         protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
1148             final DisplayResolveInfo info = params[0];
1149             if (info.displayIcon == null) {
1150                 info.displayIcon = loadIconForResolveInfo(info.ri);
1151             }
1152             return info;
1153         }
1154 
1155         @Override
onPostExecute(DisplayResolveInfo info)1156         protected void onPostExecute(DisplayResolveInfo info) {
1157             mTargetView.setImageDrawable(info.displayIcon);
1158         }
1159     }
1160 
isSpecificUriMatch(int match)1161     static final boolean isSpecificUriMatch(int match) {
1162         match = match&IntentFilter.MATCH_CATEGORY_MASK;
1163         return match >= IntentFilter.MATCH_CATEGORY_HOST
1164                 && match <= IntentFilter.MATCH_CATEGORY_PATH;
1165     }
1166 
1167     class ResolverComparator implements Comparator<ResolveInfo> {
1168         private final Collator mCollator;
1169         private final boolean mHttp;
1170 
ResolverComparator(Context context, Intent intent)1171         public ResolverComparator(Context context, Intent intent) {
1172             mCollator = Collator.getInstance(context.getResources().getConfiguration().locale);
1173             String scheme = intent.getScheme();
1174             mHttp = "http".equals(scheme) || "https".equals(scheme);
1175         }
1176 
1177         @Override
compare(ResolveInfo lhs, ResolveInfo rhs)1178         public int compare(ResolveInfo lhs, ResolveInfo rhs) {
1179             // We want to put the one targeted to another user at the end of the dialog.
1180             if (lhs.targetUserId != UserHandle.USER_CURRENT) {
1181                 return 1;
1182             }
1183 
1184             if (mHttp) {
1185                 // Special case: we want filters that match URI paths/schemes to be
1186                 // ordered before others.  This is for the case when opening URIs,
1187                 // to make native apps go above browsers.
1188                 final boolean lhsSpecific = isSpecificUriMatch(lhs.match);
1189                 final boolean rhsSpecific = isSpecificUriMatch(rhs.match);
1190                 if (lhsSpecific != rhsSpecific) {
1191                     return lhsSpecific ? -1 : 1;
1192                 }
1193             }
1194 
1195             if (mStats != null) {
1196                 final long timeDiff =
1197                         getPackageTimeSpent(rhs.activityInfo.packageName) -
1198                         getPackageTimeSpent(lhs.activityInfo.packageName);
1199 
1200                 if (timeDiff != 0) {
1201                     return timeDiff > 0 ? 1 : -1;
1202                 }
1203             }
1204 
1205             CharSequence  sa = lhs.loadLabel(mPm);
1206             if (sa == null) sa = lhs.activityInfo.name;
1207             CharSequence  sb = rhs.loadLabel(mPm);
1208             if (sb == null) sb = rhs.activityInfo.name;
1209 
1210             return mCollator.compare(sa.toString(), sb.toString());
1211         }
1212 
getPackageTimeSpent(String packageName)1213         private long getPackageTimeSpent(String packageName) {
1214             if (mStats != null) {
1215                 final UsageStats stats = mStats.get(packageName);
1216                 if (stats != null) {
1217                     return stats.getTotalTimeInForeground();
1218                 }
1219 
1220             }
1221             return 0;
1222         }
1223     }
1224 }
1225