blob: 86c13a0581c2944002b025ec1c59c0504a44382b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
17package com.android.internal.app;
18
arangelov7981b122020-01-16 10:58:27 +000019import static android.Manifest.permission.INTERACT_ACROSS_PROFILES;
Hyunyoung Song16b7af42018-10-05 14:00:42 -070020import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
arangelov7981b122020-01-16 10:58:27 +000021import static android.content.PermissionChecker.PID_UNKNOWN;
Hyunyoung Song16b7af42018-10-05 14:00:42 -070022
arangelov38a6fce2019-12-02 18:21:22 +000023import static com.android.internal.app.AbstractMultiProfilePagerAdapter.PROFILE_PERSONAL;
24import static com.android.internal.app.AbstractMultiProfilePagerAdapter.PROFILE_WORK;
25
Adam Powell4c470d62015-06-19 17:46:17 -070026import android.annotation.Nullable;
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -070027import android.annotation.StringRes;
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -080028import android.annotation.UiThread;
Adam Powelle9414d92014-07-05 17:44:18 -070029import android.app.Activity;
arangelov38a6fce2019-12-02 18:21:22 +000030import android.app.ActivityManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import android.app.ActivityTaskManager;
Dianne Hackborn028ceeb2014-08-17 17:45:48 -070032import android.app.ActivityThread;
Adam Powell4c470d62015-06-19 17:46:17 -070033import android.app.VoiceInteractor.PickOptionRequest;
34import android.app.VoiceInteractor.PickOptionRequest.Option;
35import android.app.VoiceInteractor.Prompt;
arangelov4bf17472020-02-17 20:21:46 +000036import android.app.admin.DevicePolicyEventLogger;
Artur Satayeved5a6ae2019-12-10 17:47:54 +000037import android.compat.annotation.UnsupportedAppUsage;
arangelov7f8743d2020-02-13 20:34:30 +000038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ComponentName;
40import android.content.Context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Intent;
42import android.content.IntentFilter;
arangelov7981b122020-01-16 10:58:27 +000043import android.content.PermissionChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.ActivityInfo;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +010045import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Adam Powellc5878612012-05-04 18:42:38 -070047import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.pm.ResolveInfo;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +010049import android.content.pm.UserInfo;
Jiongxuan Gao3365b162016-11-24 20:20:27 +090050import android.content.res.Configuration;
Adam Powellc5878612012-05-04 18:42:38 -070051import android.content.res.Resources;
arangelov4b8ad342020-03-17 13:56:00 +000052import android.content.res.TypedArray;
Matt Pietal800136a2019-05-08 07:46:39 -040053import android.graphics.Insets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.Uri;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +010055import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Bundle;
Alison Cichowlas3e340502018-08-07 17:15:01 -040057import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.PatternMatcher;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080059import android.os.RemoteException;
Jeff Sharkey37355a92016-02-05 16:19:10 -070060import android.os.StrictMode;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070061import android.os.UserHandle;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +010062import android.os.UserManager;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080063import android.provider.MediaStore;
64import android.provider.Settings;
arangelov4bf17472020-02-17 20:21:46 +000065import android.stats.devicepolicy.DevicePolicyEnums;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080066import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.util.Log;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080068import android.util.Slog;
arangelov4b8ad342020-03-17 13:56:00 +000069import android.util.TypedValue;
arangelovcf268642020-01-15 15:09:51 +000070import android.view.Gravity;
Adam Powell2d809622012-03-22 15:24:43 -070071import android.view.LayoutInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.View;
73import android.view.ViewGroup;
Matt Pietal800136a2019-05-08 07:46:39 -040074import android.view.ViewGroup.LayoutParams;
75import android.view.WindowInsets;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080076import android.widget.AbsListView;
Adam Powell2d809622012-03-22 15:24:43 -070077import android.widget.AdapterView;
Adam Powellc5878612012-05-04 18:42:38 -070078import android.widget.Button;
arangelovcf268642020-01-15 15:09:51 +000079import android.widget.FrameLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.widget.ImageView;
Adam Powell2d809622012-03-22 15:24:43 -070081import android.widget.ListView;
Matt Pietal800136a2019-05-08 07:46:39 -040082import android.widget.Space;
arangelovcf268642020-01-15 15:09:51 +000083import android.widget.TabHost;
84import android.widget.TabWidget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.widget.TextView;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +010086import android.widget.Toast;
Hyunyoung Song16b7af42018-10-05 14:00:42 -070087
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080088import com.android.internal.R;
89import com.android.internal.annotations.VisibleForTesting;
arangelov38a6fce2019-12-02 18:21:22 +000090import com.android.internal.app.AbstractMultiProfilePagerAdapter.Profile;
arangelov4bf17472020-02-17 20:21:46 +000091import com.android.internal.app.chooser.ChooserTargetInfo;
arangelovb0802dc2019-10-18 18:03:44 +010092import com.android.internal.app.chooser.DisplayResolveInfo;
93import com.android.internal.app.chooser.TargetInfo;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -080094import com.android.internal.content.PackageMonitor;
Clara Bayarrifa902aa2016-04-13 14:45:08 +010095import com.android.internal.logging.MetricsLogger;
Tamas Berghammer383db5eb2016-06-22 15:21:38 +010096import com.android.internal.logging.nano.MetricsProto;
Adam Powell4f6c2052014-07-07 18:49:10 -070097import com.android.internal.widget.ResolverDrawerLayout;
arangelovcf268642020-01-15 15:09:51 +000098import com.android.internal.widget.ViewPager;
Adam Powell2d809622012-03-22 15:24:43 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.ArrayList;
Clara Bayarrifa902aa2016-04-13 14:45:08 +0100101import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import java.util.Iterator;
103import java.util.List;
Adam Powellc412be62015-06-24 13:54:10 -0700104import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.Set;
106
arangelov4bf17472020-02-17 20:21:46 +0000107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108/**
109 * This activity is displayed when the system attempts to start an Intent for
110 * which there is more than one matching activity, allowing the user to decide
111 * which to go to. It is not normally used directly by application developers.
112 */
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800113@UiThread
arangelovb0802dc2019-10-18 18:03:44 +0100114public class ResolverActivity extends Activity implements
115 ResolverListAdapter.ResolverListCommunicator {
Alison Cichowlas4691ed42018-11-13 15:59:55 -0500116
Andrei Onea15884392019-03-22 17:28:11 +0000117 @UnsupportedAppUsage
Artur Satayev751e5512019-11-15 19:12:49 +0000118 public ResolverActivity() {
119 }
120
Dianne Hackborn028ceeb2014-08-17 17:45:48 -0700121 private boolean mSafeForwardingMode;
Adam Powellc5878612012-05-04 18:42:38 -0700122 private Button mAlwaysButton;
123 private Button mOnceButton;
Matt Pietal74c6ed02019-04-18 13:38:46 -0400124 protected View mProfileView;
Adam Powell24428412015-04-01 17:19:56 -0700125 private int mLastSelected = AbsListView.INVALID_POSITION;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +0100126 private boolean mResolvingHome = false;
Sander Alewijnsef6545332014-10-31 12:39:02 +0000127 private int mProfileSwitchMessageId = -1;
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800128 private int mLayoutId;
arangelovb0802dc2019-10-18 18:03:44 +0100129 @VisibleForTesting
130 protected final ArrayList<Intent> mIntents = new ArrayList<>();
Adam Powell4c470d62015-06-19 17:46:17 -0700131 private PickTargetOptionRequest mPickOptionRequest;
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800132 private String mReferrerPackage;
Hakan Seyalioglu33550122017-01-06 19:54:43 -0800133 private CharSequence mTitle;
134 private int mDefaultTitleResId;
arangelovb0802dc2019-10-18 18:03:44 +0100135
Hakan Seyalioglu13405c52017-01-31 19:01:31 -0800136 // Whether or not this activity supports choosing a default handler for the intent.
arangelovb0802dc2019-10-18 18:03:44 +0100137 @VisibleForTesting
138 protected boolean mSupportsAlwaysUseOption;
Adam Powell63b31692015-09-28 10:45:00 -0700139 protected ResolverDrawerLayout mResolverDrawerLayout;
Andrei Onea15884392019-03-22 17:28:11 +0000140 @UnsupportedAppUsage
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800141 protected PackageManager mPm;
142 protected int mLaunchedFromUid;
143
144 private static final String TAG = "ResolverActivity";
145 private static final boolean DEBUG = false;
arangelov9d894142020-04-21 21:08:21 +0100146 private static final String LAST_SHOWN_TAB_KEY = "last_shown_tab_key";
Adam Powell63b31692015-09-28 10:45:00 -0700147
Dianne Hackbornd44713a2012-04-30 16:34:46 -0700148 private boolean mRegistered;
Jorim Jaggif631ef72017-02-24 13:49:47 +0100149
Matt Pietal800136a2019-05-08 07:46:39 -0400150 protected Insets mSystemWindowInsets = null;
151 private Space mFooterSpacer = null;
152
Jorim Jaggif631ef72017-02-24 13:49:47 +0100153 /** See {@link #setRetainInOnStop}. */
154 private boolean mRetainInOnStop;
155
Matt Pietal0d6834a2019-06-27 13:27:52 -0400156 private static final String EXTRA_SHOW_FRAGMENT_ARGS = ":settings:show_fragment_args";
157 private static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
158 private static final String OPEN_LINKS_COMPONENT_KEY = "app_link_state";
arangelov4bf17472020-02-17 20:21:46 +0000159 protected static final String METRICS_CATEGORY_RESOLVER = "intent_resolver";
160 protected static final String METRICS_CATEGORY_CHOOSER = "intent_chooser";
Matt Pietal0d6834a2019-06-27 13:27:52 -0400161
arangelovcf268642020-01-15 15:09:51 +0000162 @VisibleForTesting
arangelov85974ed2020-03-06 15:48:19 +0000163 public static boolean ENABLE_TABBED_VIEW = true;
arangelovcf268642020-01-15 15:09:51 +0000164 private static final String TAB_TAG_PERSONAL = "personal";
165 private static final String TAB_TAG_WORK = "work";
arangelov38a6fce2019-12-02 18:21:22 +0000166
arangelov7981b122020-01-16 10:58:27 +0000167 private PackageMonitor mPersonalPackageMonitor;
arangelovbdb40052020-01-09 18:01:58 +0000168 private PackageMonitor mWorkPackageMonitor;
Dianne Hackborne8f2c7f2012-03-01 17:30:53 -0800169
arangelov38a6fce2019-12-02 18:21:22 +0000170 @VisibleForTesting
171 protected AbstractMultiProfilePagerAdapter mMultiProfilePagerAdapter;
172
Paul McLean07425c82019-10-18 12:00:11 -0600173 // Intent extra for connected audio devices
174 public static final String EXTRA_IS_AUDIO_CAPTURE_DEVICE = "is_audio_capture_device";
175
arangeloveb7793a2020-05-11 16:57:33 +0100176 /**
177 * Integer extra to indicate which profile should be automatically selected.
178 * <p>Can only be used if there is a work profile.
179 * <p>Possible values can be either {@link #PROFILE_PERSONAL} or {@link #PROFILE_WORK}.
180 */
181 static final String EXTRA_SELECTED_PROFILE =
182 "com.android.internal.app.ResolverActivity.EXTRA_SELECTED_PROFILE";
183
arangelov738034b2020-06-02 18:18:39 +0100184 /**
185 * {@link UserHandle} extra to indicate the user of the user that the starting intent
186 * originated from.
187 * <p>This is not necessarily the same as {@link #getUserId()} or {@link UserHandle#myUserId()},
188 * as there are edge cases when the intent resolver is launched in the other profile.
189 * For example, when we have 0 resolved apps in current profile and multiple resolved
190 * apps in the other profile, opening a link from the current profile launches the intent
191 * resolver in the other one. b/148536209 for more info.
192 */
193 static final String EXTRA_CALLING_USER =
194 "com.android.internal.app.ResolverActivity.EXTRA_CALLING_USER";
195
arangeloveb7793a2020-05-11 16:57:33 +0100196 static final int PROFILE_PERSONAL = AbstractMultiProfilePagerAdapter.PROFILE_PERSONAL;
197 static final int PROFILE_WORK = AbstractMultiProfilePagerAdapter.PROFILE_WORK;
198
arangelov7f8743d2020-02-13 20:34:30 +0000199 private BroadcastReceiver mWorkProfileStateReceiver;
arangelov4e2951b2020-04-23 18:59:09 +0100200 private UserHandle mHeaderCreatorUser;
arangelov7f8743d2020-02-13 20:34:30 +0000201
arangelov706316d2020-05-06 14:25:06 +0100202 private UserHandle mWorkProfileUserHandle;
203
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700204 /**
205 * Get the string resource to be used as a label for the link to the resolver activity for an
206 * action.
207 *
208 * @param action The action to resolve
209 *
210 * @return The string resource to be used as a label
211 */
212 public static @StringRes int getLabelRes(String action) {
213 return ActionTitle.forAction(action).labelRes;
214 }
215
Adam Powell278902c2014-07-12 18:33:22 -0700216 private enum ActionTitle {
217 VIEW(Intent.ACTION_VIEW,
218 com.android.internal.R.string.whichViewApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700219 com.android.internal.R.string.whichViewApplicationNamed,
220 com.android.internal.R.string.whichViewApplicationLabel),
Adam Powell278902c2014-07-12 18:33:22 -0700221 EDIT(Intent.ACTION_EDIT,
222 com.android.internal.R.string.whichEditApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700223 com.android.internal.R.string.whichEditApplicationNamed,
224 com.android.internal.R.string.whichEditApplicationLabel),
Adam Powell278902c2014-07-12 18:33:22 -0700225 SEND(Intent.ACTION_SEND,
226 com.android.internal.R.string.whichSendApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700227 com.android.internal.R.string.whichSendApplicationNamed,
228 com.android.internal.R.string.whichSendApplicationLabel),
Adam Powell278902c2014-07-12 18:33:22 -0700229 SENDTO(Intent.ACTION_SENDTO,
Adam Powell13ea8f42016-03-18 09:39:41 -0700230 com.android.internal.R.string.whichSendToApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700231 com.android.internal.R.string.whichSendToApplicationNamed,
232 com.android.internal.R.string.whichSendToApplicationLabel),
Adam Powell278902c2014-07-12 18:33:22 -0700233 SEND_MULTIPLE(Intent.ACTION_SEND_MULTIPLE,
234 com.android.internal.R.string.whichSendApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700235 com.android.internal.R.string.whichSendApplicationNamed,
236 com.android.internal.R.string.whichSendApplicationLabel),
237 CAPTURE_IMAGE(MediaStore.ACTION_IMAGE_CAPTURE,
238 com.android.internal.R.string.whichImageCaptureApplication,
239 com.android.internal.R.string.whichImageCaptureApplicationNamed,
240 com.android.internal.R.string.whichImageCaptureApplicationLabel),
Adam Powell278902c2014-07-12 18:33:22 -0700241 DEFAULT(null,
242 com.android.internal.R.string.whichApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700243 com.android.internal.R.string.whichApplicationNamed,
244 com.android.internal.R.string.whichApplicationLabel),
Adam Powella35c77a2014-09-25 16:46:36 -0700245 HOME(Intent.ACTION_MAIN,
246 com.android.internal.R.string.whichHomeApplication,
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700247 com.android.internal.R.string.whichHomeApplicationNamed,
248 com.android.internal.R.string.whichHomeApplicationLabel);
Adam Powell278902c2014-07-12 18:33:22 -0700249
shafik0c7c5d52019-02-27 12:13:25 +0000250 // titles for layout that deals with http(s) intents
shafik69df96322018-12-18 15:41:19 +0000251 public static final int BROWSABLE_TITLE_RES =
Matt Pietal0d6834a2019-06-27 13:27:52 -0400252 com.android.internal.R.string.whichOpenLinksWith;
253 public static final int BROWSABLE_HOST_TITLE_RES =
254 com.android.internal.R.string.whichOpenHostLinksWith;
255 public static final int BROWSABLE_HOST_APP_TITLE_RES =
256 com.android.internal.R.string.whichOpenHostLinksWithApp;
257 public static final int BROWSABLE_APP_TITLE_RES =
258 com.android.internal.R.string.whichOpenLinksWithApp;
shafik69df96322018-12-18 15:41:19 +0000259
Adam Powell278902c2014-07-12 18:33:22 -0700260 public final String action;
261 public final int titleRes;
262 public final int namedTitleRes;
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700263 public final @StringRes int labelRes;
Adam Powell278902c2014-07-12 18:33:22 -0700264
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700265 ActionTitle(String action, int titleRes, int namedTitleRes, @StringRes int labelRes) {
Adam Powell278902c2014-07-12 18:33:22 -0700266 this.action = action;
267 this.titleRes = titleRes;
268 this.namedTitleRes = namedTitleRes;
Philip P. Moltmannf8173ca2016-04-12 15:11:23 -0700269 this.labelRes = labelRes;
Adam Powell278902c2014-07-12 18:33:22 -0700270 }
271
272 public static ActionTitle forAction(String action) {
273 for (ActionTitle title : values()) {
Adam Powella35c77a2014-09-25 16:46:36 -0700274 if (title != HOME && action != null && action.equals(title.action)) {
Adam Powell278902c2014-07-12 18:33:22 -0700275 return title;
276 }
277 }
278 return DEFAULT;
279 }
280 }
281
arangelov7981b122020-01-16 10:58:27 +0000282 protected PackageMonitor createPackageMonitor(ResolverListAdapter listAdapter) {
Matt Pietalab73a882019-06-05 07:04:55 -0400283 return new PackageMonitor() {
284 @Override
285 public void onSomePackagesChanged() {
arangelov7981b122020-01-16 10:58:27 +0000286 listAdapter.handlePackagesChanged();
arangelovb0802dc2019-10-18 18:03:44 +0100287 updateProfileViewButton();
Matt Pietalab73a882019-06-05 07:04:55 -0400288 }
289
290 @Override
291 public boolean onPackageChanged(String packageName, int uid, String[] components) {
292 // We care about all package changes, not just the whole package itself which is
293 // default behavior.
294 return true;
295 }
296 };
297 }
298
Dianne Hackborn905577f2011-09-07 18:31:28 -0700299 private Intent makeMyIntent() {
300 Intent intent = new Intent(getIntent());
Dianne Hackborn6d8dfbd2013-09-23 17:38:51 -0700301 intent.setComponent(null);
Dianne Hackborn905577f2011-09-07 18:31:28 -0700302 // The resolver activity is set to be hidden from recent tasks.
303 // we don't want this attribute to be propagated to the next activity
304 // being launched. Note that if the original Intent also had this
305 // flag set, we are now losing it. That should be a very rare case
306 // and we can live with this.
307 intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
308 return intent;
309 }
310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 @Override
312 protected void onCreate(Bundle savedInstanceState) {
Christopher Tateb72b3632013-09-30 17:50:32 -0700313 // Use a specialized prompt when we're handling the 'Home' app startActivity()
Christopher Tateb72b3632013-09-30 17:50:32 -0700314 final Intent intent = makeMyIntent();
315 final Set<String> categories = intent.getCategories();
316 if (Intent.ACTION_MAIN.equals(intent.getAction())
317 && categories != null
318 && categories.size() == 1
319 && categories.contains(Intent.CATEGORY_HOME)) {
Sander Alewijnse6c9eee82014-07-17 10:03:31 +0100320 // Note: this field is not set to true in the compatibility version.
321 mResolvingHome = true;
Christopher Tateb72b3632013-09-30 17:50:32 -0700322 }
323
Dianne Hackborn028ceeb2014-08-17 17:45:48 -0700324 setSafeForwardingMode(true);
325
Adam Powella35c77a2014-09-25 16:46:36 -0700326 onCreate(savedInstanceState, intent, null, 0, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
328
Adam Powell278902c2014-07-12 18:33:22 -0700329 /**
Adam Powell24428412015-04-01 17:19:56 -0700330 * Compatibility version for other bundled services that use this overload without
Adam Powell278902c2014-07-12 18:33:22 -0700331 * a default title resource
332 */
Andrei Onea15884392019-03-22 17:28:11 +0000333 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 protected void onCreate(Bundle savedInstanceState, Intent intent,
Adam Powell278902c2014-07-12 18:33:22 -0700335 CharSequence title, Intent[] initialIntents,
Hakan Seyalioglu13405c52017-01-31 19:01:31 -0800336 List<ResolveInfo> rList, boolean supportsAlwaysUseOption) {
337 onCreate(savedInstanceState, intent, title, 0, initialIntents, rList,
338 supportsAlwaysUseOption);
Adam Powell278902c2014-07-12 18:33:22 -0700339 }
340
341 protected void onCreate(Bundle savedInstanceState, Intent intent,
342 CharSequence title, int defaultTitleRes, Intent[] initialIntents,
Hakan Seyalioglu13405c52017-01-31 19:01:31 -0800343 List<ResolveInfo> rList, boolean supportsAlwaysUseOption) {
Mike Digmand45a8b52020-05-13 12:32:19 -0700344 setTheme(appliedThemeResId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 super.onCreate(savedInstanceState);
Sander Alewijnsef6545332014-10-31 12:39:02 +0000346
347 // Determine whether we should show that intent is forwarded
348 // from managed profile to owner or other way around.
349 setProfileSwitchMessageId(intent.getContentUserHint());
350
Dianne Hackborn5320eb82012-05-18 12:05:04 -0700351 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700352 mLaunchedFromUid = ActivityTaskManager.getService().getLaunchedFromUid(
Dianne Hackborn5320eb82012-05-18 12:05:04 -0700353 getActivityToken());
354 } catch (RemoteException e) {
355 mLaunchedFromUid = -1;
356 }
Adam Powell7d758002015-05-06 17:49:36 -0700357
358 if (mLaunchedFromUid < 0 || UserHandle.isIsolated(mLaunchedFromUid)) {
359 // Gulp!
360 finish();
361 return;
362 }
363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 mPm = getPackageManager();
Adam Powell09a65602014-07-20 16:23:14 -0700365
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800366 mReferrerPackage = getReferrerPackageName();
Dianne Hackborne8f2c7f2012-03-01 17:30:53 -0800367
Adam Powell7d758002015-05-06 17:49:36 -0700368 // Add our initial intent as the first item, regardless of what else has already been added.
Adam Powell2ed547e2015-04-29 18:45:04 -0700369 mIntents.add(0, new Intent(intent));
Hakan Seyalioglu33550122017-01-06 19:54:43 -0800370 mTitle = title;
371 mDefaultTitleResId = defaultTitleRes;
Adam Powell278902c2014-07-12 18:33:22 -0700372
Matt Pietal0d6834a2019-06-27 13:27:52 -0400373 mSupportsAlwaysUseOption = supportsAlwaysUseOption;
arangelov85192182020-05-13 13:19:19 +0100374 mWorkProfileUserHandle = fetchWorkProfileUserProfile();
shafik69df96322018-12-18 15:41:19 +0000375
arangelov38a6fce2019-12-02 18:21:22 +0000376 // The last argument of createResolverListAdapter is whether to do special handling
arangelovb0802dc2019-10-18 18:03:44 +0100377 // of the last used choice to highlight it in the list. We need to always
378 // turn this off when running under voice interaction, since it results in
379 // a more complicated UI that the current voice interaction flow is not able
arangelovaa307e22020-05-07 16:14:32 +0100380 // to handle. We also turn it off when the work tab is shown to simplify the UX.
381 boolean filterLastUsed = mSupportsAlwaysUseOption && !isVoiceInteraction()
382 && !shouldShowTabs();
arangelov38a6fce2019-12-02 18:21:22 +0000383 mMultiProfilePagerAdapter = createMultiProfilePagerAdapter(initialIntents, rList, filterLastUsed);
arangelovbb572332019-11-13 12:50:08 +0000384 if (configureContentView()) {
Adam Powell39e94eb2015-09-08 17:01:49 -0700385 return;
386 }
Adam Powell278902c2014-07-12 18:33:22 -0700387
arangelov7981b122020-01-16 10:58:27 +0000388 mPersonalPackageMonitor = createPackageMonitor(
389 mMultiProfilePagerAdapter.getPersonalListAdapter());
390 mPersonalPackageMonitor.register(
391 this, getMainLooper(), getPersonalProfileUserHandle(), false);
arangelovf163a882020-02-18 17:18:47 +0000392 if (shouldShowTabs()) {
arangelov7981b122020-01-16 10:58:27 +0000393 mWorkPackageMonitor = createPackageMonitor(
394 mMultiProfilePagerAdapter.getWorkListAdapter());
395 mWorkPackageMonitor.register(this, getMainLooper(), getWorkProfileUserHandle(), false);
396 }
397
398 mRegistered = true;
399
Alan Viverette51efddb2017-04-05 10:00:01 -0400400 final ResolverDrawerLayout rdl = findViewById(R.id.contentPanel);
Adam Powell4f6c2052014-07-07 18:49:10 -0700401 if (rdl != null) {
Adam Powell5dd072d2014-10-30 19:51:41 -0700402 rdl.setOnDismissedListener(new ResolverDrawerLayout.OnDismissedListener() {
Adam Powell4f6c2052014-07-07 18:49:10 -0700403 @Override
Adam Powell5dd072d2014-10-30 19:51:41 -0700404 public void onDismissed() {
Adam Powell4f6c2052014-07-07 18:49:10 -0700405 finish();
406 }
407 });
Sergey Troshin40e979e2019-12-30 17:29:50 +0100408
409 boolean hasTouchScreen = getPackageManager()
410 .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN);
411
412 if (isVoiceInteraction() || !hasTouchScreen) {
Adam Powell4c470d62015-06-19 17:46:17 -0700413 rdl.setCollapsed(false);
414 }
Matt Pietal800136a2019-05-08 07:46:39 -0400415
416 rdl.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
417 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
418 rdl.setOnApplyWindowInsetsListener(this::onApplyWindowInsets);
419
Adam Powell63b31692015-09-28 10:45:00 -0700420 mResolverDrawerLayout = rdl;
Adam Powell4f6c2052014-07-07 18:49:10 -0700421 }
422
Adam Powell88831a22014-11-20 18:17:00 -0800423 mProfileView = findViewById(R.id.profile_button);
424 if (mProfileView != null) {
Matt Pietal74c6ed02019-04-18 13:38:46 -0400425 mProfileView.setOnClickListener(this::onProfileClick);
arangelovb0802dc2019-10-18 18:03:44 +0100426 updateProfileViewButton();
Adam Powell88831a22014-11-20 18:17:00 -0800427 }
Adam Powell4c470d62015-06-19 17:46:17 -0700428
Clara Bayarri9550f5d2016-05-11 11:20:13 +0100429 final Set<String> categories = intent.getCategories();
arangelova3912cf2019-12-13 14:34:45 +0000430 MetricsLogger.action(this, mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem()
Clara Bayarrifa902aa2016-04-13 14:45:08 +0100431 ? MetricsProto.MetricsEvent.ACTION_SHOW_APP_DISAMBIG_APP_FEATURED
432 : MetricsProto.MetricsEvent.ACTION_SHOW_APP_DISAMBIG_NONE_FEATURED,
433 intent.getAction() + ":" + intent.getType() + ":"
Clara Bayarri9550f5d2016-05-11 11:20:13 +0100434 + (categories != null ? Arrays.toString(categories.toArray()) : ""));
Adam Powell4c470d62015-06-19 17:46:17 -0700435 }
436
arangelovc4dbdbd2020-02-18 20:54:16 +0000437 private boolean isIntentPicker() {
438 return getClass().equals(ResolverActivity.class);
439 }
440
arangelov38a6fce2019-12-02 18:21:22 +0000441 protected AbstractMultiProfilePagerAdapter createMultiProfilePagerAdapter(
442 Intent[] initialIntents,
443 List<ResolveInfo> rList,
444 boolean filterLastUsed) {
445 AbstractMultiProfilePagerAdapter resolverMultiProfilePagerAdapter = null;
arangelovf163a882020-02-18 17:18:47 +0000446 if (shouldShowTabs()) {
arangelov38a6fce2019-12-02 18:21:22 +0000447 resolverMultiProfilePagerAdapter =
448 createResolverMultiProfilePagerAdapterForTwoProfiles(
449 initialIntents, rList, filterLastUsed);
450 } else {
451 resolverMultiProfilePagerAdapter = createResolverMultiProfilePagerAdapterForOneProfile(
452 initialIntents, rList, filterLastUsed);
453 }
454 return resolverMultiProfilePagerAdapter;
455 }
456
457 private ResolverMultiProfilePagerAdapter createResolverMultiProfilePagerAdapterForOneProfile(
458 Intent[] initialIntents,
459 List<ResolveInfo> rList, boolean filterLastUsed) {
460 ResolverListAdapter adapter = createResolverListAdapter(
461 /* context */ this,
462 /* payloadIntents */ mIntents,
463 initialIntents,
464 rList,
465 filterLastUsed,
arangelov38a6fce2019-12-02 18:21:22 +0000466 /* userHandle */ UserHandle.of(UserHandle.myUserId()));
467 return new ResolverMultiProfilePagerAdapter(
468 /* context */ this,
arangelov7981b122020-01-16 10:58:27 +0000469 adapter,
470 getPersonalProfileUserHandle(),
471 /* workProfileUserHandle= */ null);
arangelov38a6fce2019-12-02 18:21:22 +0000472 }
473
474 private ResolverMultiProfilePagerAdapter createResolverMultiProfilePagerAdapterForTwoProfiles(
475 Intent[] initialIntents,
476 List<ResolveInfo> rList,
477 boolean filterLastUsed) {
arangelov2c6115a2020-04-08 13:26:13 +0100478 // In the edge case when we have 0 apps in the current profile and >1 apps in the other,
479 // the intent resolver is started in the other profile. Since this is the only case when
480 // this happens, we check for it here and set the current profile's tab.
481 int selectedProfile = getCurrentProfile();
arangelov738034b2020-06-02 18:18:39 +0100482 UserHandle intentUser = getIntent().hasExtra(EXTRA_CALLING_USER)
483 ? getIntent().getParcelableExtra(EXTRA_CALLING_USER)
484 : getUser();
arangelov2c6115a2020-04-08 13:26:13 +0100485 if (!getUser().equals(intentUser)) {
486 if (getPersonalProfileUserHandle().equals(intentUser)) {
487 selectedProfile = PROFILE_PERSONAL;
488 } else if (getWorkProfileUserHandle().equals(intentUser)) {
489 selectedProfile = PROFILE_WORK;
490 }
arangelov738034b2020-06-02 18:18:39 +0100491 } else {
492 int selectedProfileExtra = getSelectedProfileExtra();
493 if (selectedProfileExtra != -1) {
494 selectedProfile = selectedProfileExtra;
495 }
arangeloveb7793a2020-05-11 16:57:33 +0100496 }
arangelovacc82432020-04-28 12:55:55 +0100497 // We only show the default app for the profile of the current user. The filterLastUsed
498 // flag determines whether to show a default app and that app is not shown in the
499 // resolver list. So filterLastUsed should be false for the other profile.
500 ResolverListAdapter personalAdapter = createResolverListAdapter(
501 /* context */ this,
502 /* payloadIntents */ mIntents,
503 selectedProfile == PROFILE_PERSONAL ? initialIntents : null,
504 rList,
505 (filterLastUsed && UserHandle.myUserId()
506 == getPersonalProfileUserHandle().getIdentifier()),
arangelovacc82432020-04-28 12:55:55 +0100507 /* userHandle */ getPersonalProfileUserHandle());
508 UserHandle workProfileUserHandle = getWorkProfileUserHandle();
509 ResolverListAdapter workAdapter = createResolverListAdapter(
510 /* context */ this,
511 /* payloadIntents */ mIntents,
512 selectedProfile == PROFILE_WORK ? initialIntents : null,
513 rList,
514 (filterLastUsed && UserHandle.myUserId()
515 == workProfileUserHandle.getIdentifier()),
arangelovacc82432020-04-28 12:55:55 +0100516 /* userHandle */ workProfileUserHandle);
arangelov38a6fce2019-12-02 18:21:22 +0000517 return new ResolverMultiProfilePagerAdapter(
518 /* context */ this,
519 personalAdapter,
520 workAdapter,
arangelov2c6115a2020-04-08 13:26:13 +0100521 selectedProfile,
arangelov7981b122020-01-16 10:58:27 +0000522 getPersonalProfileUserHandle(),
arangelov2c6115a2020-04-08 13:26:13 +0100523 getWorkProfileUserHandle(),
524 /* shouldShowNoCrossProfileIntentsEmptyState= */ getUser().equals(intentUser));
525 }
526
Mike Digmand45a8b52020-05-13 12:32:19 -0700527 protected int appliedThemeResId() {
528 return R.style.Theme_DeviceDefault_Resolver;
529 }
530
arangelov2c6115a2020-04-08 13:26:13 +0100531 /**
arangeloveb7793a2020-05-11 16:57:33 +0100532 * Returns {@link #PROFILE_PERSONAL} or {@link #PROFILE_WORK} if the {@link
533 * #EXTRA_SELECTED_PROFILE} extra was supplied, or {@code -1} if no extra was supplied.
534 * @throws IllegalArgumentException if the value passed to the {@link #EXTRA_SELECTED_PROFILE}
535 * extra is not {@link #PROFILE_PERSONAL} or {@link #PROFILE_WORK}
536 */
537 int getSelectedProfileExtra() {
538 int selectedProfile = -1;
539 if (getIntent().hasExtra(EXTRA_SELECTED_PROFILE)) {
540 selectedProfile = getIntent().getIntExtra(EXTRA_SELECTED_PROFILE, /* defValue = */ -1);
541 if (selectedProfile != PROFILE_PERSONAL && selectedProfile != PROFILE_WORK) {
542 throw new IllegalArgumentException(EXTRA_SELECTED_PROFILE + " has invalid value "
543 + selectedProfile + ". Must be either ResolverActivity.PROFILE_PERSONAL or "
544 + "ResolverActivity.PROFILE_WORK.");
545 }
546 }
547 return selectedProfile;
548 }
549
arangelov38a6fce2019-12-02 18:21:22 +0000550 protected @Profile int getCurrentProfile() {
551 return (UserHandle.myUserId() == UserHandle.USER_SYSTEM ? PROFILE_PERSONAL : PROFILE_WORK);
552 }
553
554 protected UserHandle getPersonalProfileUserHandle() {
555 return UserHandle.of(ActivityManager.getCurrentUser());
556 }
557 protected @Nullable UserHandle getWorkProfileUserHandle() {
arangelov706316d2020-05-06 14:25:06 +0100558 return mWorkProfileUserHandle;
559 }
560
561 protected @Nullable UserHandle fetchWorkProfileUserProfile() {
562 mWorkProfileUserHandle = null;
arangelov38a6fce2019-12-02 18:21:22 +0000563 UserManager userManager = getSystemService(UserManager.class);
564 for (final UserInfo userInfo : userManager.getProfiles(ActivityManager.getCurrentUser())) {
565 if (userInfo.isManagedProfile()) {
arangelov706316d2020-05-06 14:25:06 +0100566 mWorkProfileUserHandle = userInfo.getUserHandle();
arangelov38a6fce2019-12-02 18:21:22 +0000567 }
568 }
arangelov706316d2020-05-06 14:25:06 +0100569 return mWorkProfileUserHandle;
arangelov38a6fce2019-12-02 18:21:22 +0000570 }
571
arangelovf163a882020-02-18 17:18:47 +0000572 private boolean hasWorkProfile() {
arangelov38a6fce2019-12-02 18:21:22 +0000573 return getWorkProfileUserHandle() != null;
574 }
575
arangelovf163a882020-02-18 17:18:47 +0000576 protected boolean shouldShowTabs() {
577 return hasWorkProfile() && ENABLE_TABBED_VIEW;
578 }
579
Matt Pietal74c6ed02019-04-18 13:38:46 -0400580 protected void onProfileClick(View v) {
arangelov38a6fce2019-12-02 18:21:22 +0000581 final DisplayResolveInfo dri =
arangelova3912cf2019-12-13 14:34:45 +0000582 mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile();
Matt Pietal74c6ed02019-04-18 13:38:46 -0400583 if (dri == null) {
584 return;
585 }
586
587 // Do not show the profile switch message anymore.
588 mProfileSwitchMessageId = -1;
589
590 onTargetSelected(dri, false);
591 finish();
592 }
593
Matt Pietal9236adc2019-12-12 09:24:23 -0500594 /**
595 * Numerous layouts are supported, each with optional ViewGroups.
596 * Make sure the inset gets added to the correct View, using
597 * a footer for Lists so it can properly scroll under the navbar.
598 */
599 protected boolean shouldAddFooterView() {
600 if (useLayoutWithDefault()) return true;
601
602 View buttonBar = findViewById(R.id.button_bar);
603 if (buttonBar == null || buttonBar.getVisibility() == View.GONE) return true;
604
605 return false;
606 }
607
608 protected void applyFooterView(int height) {
609 if (mFooterSpacer == null) {
610 mFooterSpacer = new Space(getApplicationContext());
611 } else {
612 ((ResolverMultiProfilePagerAdapter) mMultiProfilePagerAdapter)
arangelovcf268642020-01-15 15:09:51 +0000613 .getActiveAdapterView().removeFooterView(mFooterSpacer);
Matt Pietal9236adc2019-12-12 09:24:23 -0500614 }
615 mFooterSpacer.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT,
616 mSystemWindowInsets.bottom));
617 ((ResolverMultiProfilePagerAdapter) mMultiProfilePagerAdapter)
arangelovcf268642020-01-15 15:09:51 +0000618 .getActiveAdapterView().addFooterView(mFooterSpacer);
Matt Pietal9236adc2019-12-12 09:24:23 -0500619 }
620
Matt Pietal800136a2019-05-08 07:46:39 -0400621 protected WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
622 mSystemWindowInsets = insets.getSystemWindowInsets();
623
624 mResolverDrawerLayout.setPadding(mSystemWindowInsets.left, mSystemWindowInsets.top,
625 mSystemWindowInsets.right, 0);
626
Matt Pietal9236adc2019-12-12 09:24:23 -0500627 resetButtonBar();
628
Matt Pietald5071202019-10-10 11:21:28 -0400629 // Need extra padding so the list can fully scroll up
Matt Pietal9236adc2019-12-12 09:24:23 -0500630 if (shouldAddFooterView()) {
631 applyFooterView(mSystemWindowInsets.bottom);
Matt Pietal800136a2019-05-08 07:46:39 -0400632 }
Matt Pietal800136a2019-05-08 07:46:39 -0400633
634 return insets.consumeSystemWindowInsets();
635 }
636
Jiongxuan Gao3365b162016-11-24 20:20:27 +0900637 @Override
638 public void onConfigurationChanged(Configuration newConfig) {
639 super.onConfigurationChanged(newConfig);
arangelova3912cf2019-12-13 14:34:45 +0000640 mMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
arangelov981e4142020-05-27 15:59:18 +0100641 if (isIntentPicker() && shouldShowTabs() && !useLayoutWithDefault()) {
642 updateIntentPickerPaddings();
643 }
Matt Pietal800136a2019-05-08 07:46:39 -0400644
645 if (mSystemWindowInsets != null) {
646 mResolverDrawerLayout.setPadding(mSystemWindowInsets.left, mSystemWindowInsets.top,
647 mSystemWindowInsets.right, 0);
648 }
Jiongxuan Gao3365b162016-11-24 20:20:27 +0900649 }
650
arangelov981e4142020-05-27 15:59:18 +0100651 private void updateIntentPickerPaddings() {
652 View titleCont = findViewById(R.id.title_container);
653 titleCont.setPadding(
654 titleCont.getPaddingLeft(),
655 titleCont.getPaddingTop(),
656 titleCont.getPaddingRight(),
657 getResources().getDimensionPixelSize(R.dimen.resolver_title_padding_bottom));
658 View buttonBar = findViewById(R.id.button_bar);
659 buttonBar.setPadding(
660 buttonBar.getPaddingLeft(),
661 getResources().getDimensionPixelSize(R.dimen.resolver_button_bar_spacing),
662 buttonBar.getPaddingRight(),
663 getResources().getDimensionPixelSize(R.dimen.resolver_button_bar_spacing));
664 mMultiProfilePagerAdapter.updateAfterConfigChange();
665 }
666
arangelovb0802dc2019-10-18 18:03:44 +0100667 @Override // ResolverListCommunicator
Adam Powell23882512016-01-29 10:21:00 -0800668 public void sendVoiceChoicesIfNeeded() {
Adam Powell4c470d62015-06-19 17:46:17 -0700669 if (!isVoiceInteraction()) {
670 // Clearly not needed.
671 return;
672 }
673
arangelova3912cf2019-12-13 14:34:45 +0000674 int count = mMultiProfilePagerAdapter.getActiveListAdapter().getCount();
arangelov38a6fce2019-12-02 18:21:22 +0000675 final Option[] options = new Option[count];
Adam Powell4c470d62015-06-19 17:46:17 -0700676 for (int i = 0, N = options.length; i < N; i++) {
arangelova3912cf2019-12-13 14:34:45 +0000677 TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter().getItem(i);
Matt Pietal2cf4c6c2019-09-10 09:33:11 -0400678 if (target == null) {
679 // If this occurs, a new set of targets is being loaded. Let that complete,
680 // and have the next call to send voice choices proceed instead.
681 return;
682 }
683 options[i] = optionForChooserTarget(target, i);
Adam Powell4c470d62015-06-19 17:46:17 -0700684 }
685
686 mPickOptionRequest = new PickTargetOptionRequest(
687 new Prompt(getTitle()), options, null);
688 getVoiceInteractor().submitRequest(mPickOptionRequest);
689 }
690
691 Option optionForChooserTarget(TargetInfo target, int index) {
692 return new Option(target.getDisplayLabel(), index);
Adam Powell88831a22014-11-20 18:17:00 -0800693 }
694
Adam Powell2ed547e2015-04-29 18:45:04 -0700695 protected final void setAdditionalTargets(Intent[] intents) {
696 if (intents != null) {
697 for (Intent intent : intents) {
698 mIntents.add(intent);
699 }
700 }
701 }
702
arangelovb0802dc2019-10-18 18:03:44 +0100703 @Override // SelectableTargetInfoCommunicator ResolverListCommunicator
Adam Powell0ccc0e92015-04-23 17:19:37 -0700704 public Intent getTargetIntent() {
Adam Powell2ed547e2015-04-29 18:45:04 -0700705 return mIntents.isEmpty() ? null : mIntents.get(0);
Adam Powell0ccc0e92015-04-23 17:19:37 -0700706 }
707
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800708 protected String getReferrerPackageName() {
Adam Powell24428412015-04-01 17:19:56 -0700709 final Uri referrer = getReferrer();
710 if (referrer != null && "android-app".equals(referrer.getScheme())) {
711 return referrer.getHost();
712 }
713 return null;
714 }
715
Adam Powell23882512016-01-29 10:21:00 -0800716 public int getLayoutResource() {
Adam Powell24428412015-04-01 17:19:56 -0700717 return R.layout.resolver_list;
718 }
719
arangelovb0802dc2019-10-18 18:03:44 +0100720 @Override // ResolverListCommunicator
721 public void updateProfileViewButton() {
Matt Pietal74c6ed02019-04-18 13:38:46 -0400722 if (mProfileView == null) {
723 return;
724 }
725
arangelov38a6fce2019-12-02 18:21:22 +0000726 final DisplayResolveInfo dri =
arangelova3912cf2019-12-13 14:34:45 +0000727 mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile();
arangelov2a4d0b12020-03-04 18:15:04 +0000728 if (dri != null && !shouldShowTabs()) {
Adam Powell88831a22014-11-20 18:17:00 -0800729 mProfileView.setVisibility(View.VISIBLE);
Hakan Seyalioglu13405c52017-01-31 19:01:31 -0800730 View text = mProfileView.findViewById(R.id.profile_button);
731 if (!(text instanceof TextView)) {
732 text = mProfileView.findViewById(R.id.text1);
733 }
734 ((TextView) text).setText(dri.getDisplayLabel());
Adam Powell88831a22014-11-20 18:17:00 -0800735 } else {
736 mProfileView.setVisibility(View.GONE);
737 }
Adam Powell278902c2014-07-12 18:33:22 -0700738 }
739
Sander Alewijnsef6545332014-10-31 12:39:02 +0000740 private void setProfileSwitchMessageId(int contentUserHint) {
741 if (contentUserHint != UserHandle.USER_CURRENT &&
742 contentUserHint != UserHandle.myUserId()) {
743 UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
744 UserInfo originUserInfo = userManager.getUserInfo(contentUserHint);
745 boolean originIsManaged = originUserInfo != null ? originUserInfo.isManagedProfile()
746 : false;
747 boolean targetIsManaged = userManager.isManagedProfile();
748 if (originIsManaged && !targetIsManaged) {
749 mProfileSwitchMessageId = com.android.internal.R.string.forward_intent_to_owner;
750 } else if (!originIsManaged && targetIsManaged) {
751 mProfileSwitchMessageId = com.android.internal.R.string.forward_intent_to_work;
752 }
753 }
754 }
755
Dianne Hackborn028ceeb2014-08-17 17:45:48 -0700756 /**
757 * Turn on launch mode that is safe to use when forwarding intents received from
758 * applications and running in system processes. This mode uses Activity.startActivityAsCaller
759 * instead of the normal Activity.startActivity for launching the activity selected
760 * by the user.
761 *
762 * <p>This mode is set to true by default if the activity is initialized through
763 * {@link #onCreate(android.os.Bundle)}. If a subclass calls one of the other onCreate
764 * methods, it is set to false by default. You must set it before calling one of the
765 * more detailed onCreate methods, so that it will be set correctly in the case where
766 * there is only one intent to resolve and it is thus started immediately.</p>
767 */
768 public void setSafeForwardingMode(boolean safeForwarding) {
769 mSafeForwardingMode = safeForwarding;
770 }
771
shafik69df96322018-12-18 15:41:19 +0000772 protected CharSequence getTitleForAction(Intent intent, int defaultTitleRes) {
773 final ActionTitle title = mResolvingHome
774 ? ActionTitle.HOME
775 : ActionTitle.forAction(intent.getAction());
776
Hakan Seyalioglu23f34652017-02-03 09:38:35 -0800777 // While there may already be a filtered item, we can only use it in the title if the list
778 // is already sorted and all information relevant to it is already in the list.
arangelov38a6fce2019-12-02 18:21:22 +0000779 final boolean named =
arangelova3912cf2019-12-13 14:34:45 +0000780 mMultiProfilePagerAdapter.getActiveListAdapter().getFilteredPosition() >= 0;
Adam Powell278902c2014-07-12 18:33:22 -0700781 if (title == ActionTitle.DEFAULT && defaultTitleRes != 0) {
782 return getString(defaultTitleRes);
783 } else {
Adam Powell24428412015-04-01 17:19:56 -0700784 return named
arangelov38a6fce2019-12-02 18:21:22 +0000785 ? getString(title.namedTitleRes, mMultiProfilePagerAdapter
arangelova3912cf2019-12-13 14:34:45 +0000786 .getActiveListAdapter().getFilteredItem().getDisplayLabel())
Adam Powell24428412015-04-01 17:19:56 -0700787 : getString(title.titleRes);
Amith Yamasanie9ecc8b2013-08-22 11:16:27 -0700788 }
Adam Powellc5878612012-05-04 18:42:38 -0700789 }
790
Adam Powelle9414d92014-07-05 17:44:18 -0700791 void dismiss() {
792 if (!isFinishing()) {
793 finish();
794 }
795 }
796
Dianne Hackborne8f2c7f2012-03-01 17:30:53 -0800797 @Override
798 protected void onRestart() {
799 super.onRestart();
Dianne Hackbornd44713a2012-04-30 16:34:46 -0700800 if (!mRegistered) {
arangelovbdb40052020-01-09 18:01:58 +0000801 mPersonalPackageMonitor.register(this, getMainLooper(),
802 getPersonalProfileUserHandle(), false);
arangelovf163a882020-02-18 17:18:47 +0000803 if (shouldShowTabs()) {
arangelovbdb40052020-01-09 18:01:58 +0000804 if (mWorkPackageMonitor == null) {
arangelov7981b122020-01-16 10:58:27 +0000805 mWorkPackageMonitor = createPackageMonitor(
806 mMultiProfilePagerAdapter.getWorkListAdapter());
arangelovbdb40052020-01-09 18:01:58 +0000807 }
808 mWorkPackageMonitor.register(this, getMainLooper(),
809 getWorkProfileUserHandle(), false);
810 }
Dianne Hackbornd44713a2012-04-30 16:34:46 -0700811 mRegistered = true;
812 }
arangelovafec9d02020-03-17 12:41:01 +0000813 if (shouldShowTabs() && mMultiProfilePagerAdapter.isWaitingToEnableWorkProfile()) {
814 if (mMultiProfilePagerAdapter.isQuietModeEnabled(getWorkProfileUserHandle())) {
815 mMultiProfilePagerAdapter.markWorkProfileEnabledBroadcastReceived();
816 }
817 }
arangelova3912cf2019-12-13 14:34:45 +0000818 mMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
arangelovb0802dc2019-10-18 18:03:44 +0100819 updateProfileViewButton();
Dianne Hackborne8f2c7f2012-03-01 17:30:53 -0800820 }
821
822 @Override
arangelov7f8743d2020-02-13 20:34:30 +0000823 protected void onStart() {
824 super.onStart();
arangelovf163a882020-02-18 17:18:47 +0000825 if (shouldShowTabs()) {
arangelov7f8743d2020-02-13 20:34:30 +0000826 mWorkProfileStateReceiver = createWorkProfileStateReceiver();
827 registerWorkProfileStateReceiver();
828 }
829 }
830
831 private void registerWorkProfileStateReceiver() {
832 IntentFilter filter = new IntentFilter();
arangelov2dd9f7b2020-02-27 10:54:24 +0000833 filter.addAction(Intent.ACTION_USER_UNLOCKED);
arangelov7f8743d2020-02-13 20:34:30 +0000834 filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
835 registerReceiverAsUser(mWorkProfileStateReceiver, UserHandle.ALL, filter, null, null);
836 }
837
838 @Override
Dianne Hackborne8f2c7f2012-03-01 17:30:53 -0800839 protected void onStop() {
840 super.onStop();
Dianne Hackbornd44713a2012-04-30 16:34:46 -0700841 if (mRegistered) {
arangelovbdb40052020-01-09 18:01:58 +0000842 mPersonalPackageMonitor.unregister();
843 if (mWorkPackageMonitor != null) {
844 mWorkPackageMonitor.unregister();
845 }
Dianne Hackbornd44713a2012-04-30 16:34:46 -0700846 mRegistered = false;
847 }
Wale Ogunwale9014e662016-03-19 14:55:46 -0700848 final Intent intent = getIntent();
849 if ((intent.getFlags() & FLAG_ACTIVITY_NEW_TASK) != 0 && !isVoiceInteraction()
Jorim Jaggif631ef72017-02-24 13:49:47 +0100850 && !mResolvingHome && !mRetainInOnStop) {
Dianne Hackborn5320eb82012-05-18 12:05:04 -0700851 // This resolver is in the unusual situation where it has been
852 // launched at the top of a new task. We don't let it be added
853 // to the recent tasks shown to the user, and we need to make sure
854 // that each time we are launched we get the correct launching
855 // uid (not re-using the same resolver from an old launching uid),
856 // so we will now finish ourself since being no longer visible,
857 // the user probably can't get back to us.
858 if (!isChangingConfigurations()) {
859 finish();
860 }
861 }
arangelov7f8743d2020-02-13 20:34:30 +0000862 if (mWorkPackageMonitor != null) {
863 unregisterReceiver(mWorkProfileStateReceiver);
864 mWorkPackageMonitor = null;
865 }
Dianne Hackborne8f2c7f2012-03-01 17:30:53 -0800866 }
867
Adam Powellc5878612012-05-04 18:42:38 -0700868 @Override
Adam Powell4c470d62015-06-19 17:46:17 -0700869 protected void onDestroy() {
870 super.onDestroy();
871 if (!isChangingConfigurations() && mPickOptionRequest != null) {
872 mPickOptionRequest.cancel();
873 }
arangelova3912cf2019-12-13 14:34:45 +0000874 if (mMultiProfilePagerAdapter.getActiveListAdapter() != null) {
875 mMultiProfilePagerAdapter.getActiveListAdapter().onDestroy();
Kang Li38a6da642017-04-05 12:30:55 -0700876 }
Adam Powell4c470d62015-06-19 17:46:17 -0700877 }
878
879 @Override
arangelov9d894142020-04-21 21:08:21 +0100880 protected void onSaveInstanceState(Bundle outState) {
881 super.onSaveInstanceState(outState);
882 ViewPager viewPager = findViewById(R.id.profile_pager);
883 outState.putInt(LAST_SHOWN_TAB_KEY, viewPager.getCurrentItem());
884 }
885
886 @Override
Adam Powell9bee4662012-05-08 11:07:23 -0700887 protected void onRestoreInstanceState(Bundle savedInstanceState) {
888 super.onRestoreInstanceState(savedInstanceState);
shafik69df96322018-12-18 15:41:19 +0000889 resetButtonBar();
arangelov9d894142020-04-21 21:08:21 +0100890 ViewPager viewPager = findViewById(R.id.profile_pager);
891 viewPager.setCurrentItem(savedInstanceState.getInt(LAST_SHOWN_TAB_KEY));
892 mMultiProfilePagerAdapter.clearInactiveProfileCache();
Adam Powell9bee4662012-05-08 11:07:23 -0700893 }
894
Sander Alewijnse6c9eee82014-07-17 10:03:31 +0100895 private boolean hasManagedProfile() {
896 UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
897 if (userManager == null) {
898 return false;
899 }
900
901 try {
902 List<UserInfo> profiles = userManager.getProfiles(getUserId());
903 for (UserInfo userInfo : profiles) {
904 if (userInfo != null && userInfo.isManagedProfile()) {
905 return true;
906 }
907 }
908 } catch (SecurityException e) {
909 return false;
910 }
911 return false;
912 }
913
914 private boolean supportsManagedProfiles(ResolveInfo resolveInfo) {
915 try {
916 ApplicationInfo appInfo = getPackageManager().getApplicationInfo(
917 resolveInfo.activityInfo.packageName, 0 /* default flags */);
Adam Powell4c470d62015-06-19 17:46:17 -0700918 return appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
Sander Alewijnse6c9eee82014-07-17 10:03:31 +0100919 } catch (NameNotFoundException e) {
920 return false;
921 }
922 }
923
Adam Powell278902c2014-07-12 18:33:22 -0700924 private void setAlwaysButtonEnabled(boolean hasValidSelection, int checkedPos,
925 boolean filtered) {
arangelov2c6115a2020-04-08 13:26:13 +0100926 if (!mMultiProfilePagerAdapter.getCurrentUserHandle().equals(getUser())) {
arangelov349af6a2020-03-05 11:53:40 +0000927 // Never allow the inactive profile to always open an app.
928 mAlwaysButton.setEnabled(false);
929 return;
930 }
Nicolas Prevot50449882014-06-23 12:42:37 +0100931 boolean enabled = false;
Paul McLean3a30e552019-12-07 14:47:29 -0700932 ResolveInfo ri = null;
Nicolas Prevot50449882014-06-23 12:42:37 +0100933 if (hasValidSelection) {
arangelova3912cf2019-12-13 14:34:45 +0000934 ri = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +0000935 .resolveInfoForPosition(checkedPos, filtered);
Hakan Seyalioglu5dbc8192017-02-24 16:16:37 -0800936 if (ri == null) {
937 Log.e(TAG, "Invalid position supplied to setAlwaysButtonEnabled");
938 return;
939 } else if (ri.targetUserId != UserHandle.USER_CURRENT) {
940 Log.e(TAG, "Attempted to set selection to resolve info for another user");
941 return;
942 } else {
Nicolas Prevot50449882014-06-23 12:42:37 +0100943 enabled = true;
944 }
Narayan Kamath75418682020-05-07 13:42:05 +0100945
946 mAlwaysButton.setText(getResources()
947 .getString(R.string.activity_resolver_use_always));
Nicolas Prevot50449882014-06-23 12:42:37 +0100948 }
Paul McLean3a30e552019-12-07 14:47:29 -0700949
arangelov349af6a2020-03-05 11:53:40 +0000950 if (ri != null) {
951 ActivityInfo activityInfo = ri.activityInfo;
Paul McLean3a30e552019-12-07 14:47:29 -0700952
arangelov349af6a2020-03-05 11:53:40 +0000953 boolean hasRecordPermission =
954 mPm.checkPermission(android.Manifest.permission.RECORD_AUDIO,
955 activityInfo.packageName)
956 == android.content.pm.PackageManager.PERMISSION_GRANTED;
Paul McLean3a30e552019-12-07 14:47:29 -0700957
arangelov349af6a2020-03-05 11:53:40 +0000958 if (!hasRecordPermission) {
959 // OK, we know the record permission, is this a capture device
960 boolean hasAudioCapture =
961 getIntent().getBooleanExtra(
962 ResolverActivity.EXTRA_IS_AUDIO_CAPTURE_DEVICE, false);
963 enabled = !hasAudioCapture;
964 }
Paul McLean3a30e552019-12-07 14:47:29 -0700965 }
Nicolas Prevot50449882014-06-23 12:42:37 +0100966 mAlwaysButton.setEnabled(enabled);
967 }
968
Adam Powellc5878612012-05-04 18:42:38 -0700969 public void onButtonClick(View v) {
970 final int id = v.getId();
arangelovcf268642020-01-15 15:09:51 +0000971 ListView listView = (ListView) mMultiProfilePagerAdapter.getActiveAdapterView();
arangelova3912cf2019-12-13 14:34:45 +0000972 ResolverListAdapter currentListAdapter = mMultiProfilePagerAdapter.getActiveListAdapter();
arangelov38a6fce2019-12-02 18:21:22 +0000973 int which = currentListAdapter.hasFilteredItem()
974 ? currentListAdapter.getFilteredPosition()
975 : listView.getCheckedItemPosition();
976 boolean hasIndexBeenFiltered = !currentListAdapter.hasFilteredItem();
Narayan Kamath75418682020-05-07 13:42:05 +0100977 startSelected(which, id == R.id.button_always, hasIndexBeenFiltered);
Adam Powellc5878612012-05-04 18:42:38 -0700978 }
979
Hakan Seyalioglu13405c52017-01-31 19:01:31 -0800980 public void startSelected(int which, boolean always, boolean hasIndexBeenFiltered) {
Amith Yamasani07cd3512013-09-18 13:16:00 -0700981 if (isFinishing()) {
982 return;
983 }
arangelova3912cf2019-12-13 14:34:45 +0000984 ResolveInfo ri = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +0000985 .resolveInfoForPosition(which, hasIndexBeenFiltered);
Sander Alewijnse86d35ba2015-02-04 15:14:53 +0000986 if (mResolvingHome && hasManagedProfile() && !supportsManagedProfiles(ri)) {
987 Toast.makeText(this, String.format(getResources().getString(
988 com.android.internal.R.string.activity_resolver_work_profiles_support),
989 ri.activityInfo.loadLabel(getPackageManager()).toString()),
990 Toast.LENGTH_LONG).show();
991 return;
992 }
993
arangelova3912cf2019-12-13 14:34:45 +0000994 TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +0000995 .targetInfoForPosition(which, hasIndexBeenFiltered);
Hakan Seyalioglu23f34652017-02-03 09:38:35 -0800996 if (target == null) {
997 return;
998 }
Adam Powell2ed547e2015-04-29 18:45:04 -0700999 if (onTargetSelected(target, always)) {
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001000 if (always && mSupportsAlwaysUseOption) {
Clara Bayarrifa902aa2016-04-13 14:45:08 +01001001 MetricsLogger.action(
1002 this, MetricsProto.MetricsEvent.ACTION_APP_DISAMBIG_ALWAYS);
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001003 } else if (mSupportsAlwaysUseOption) {
Clara Bayarrifa902aa2016-04-13 14:45:08 +01001004 MetricsLogger.action(
1005 this, MetricsProto.MetricsEvent.ACTION_APP_DISAMBIG_JUST_ONCE);
1006 } else {
1007 MetricsLogger.action(
1008 this, MetricsProto.MetricsEvent.ACTION_APP_DISAMBIG_TAP);
1009 }
arangelov38a6fce2019-12-02 18:21:22 +00001010 MetricsLogger.action(this,
arangelova3912cf2019-12-13 14:34:45 +00001011 mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem()
Clara Bayarrifa902aa2016-04-13 14:45:08 +01001012 ? MetricsProto.MetricsEvent.ACTION_HIDE_APP_DISAMBIG_APP_FEATURED
1013 : MetricsProto.MetricsEvent.ACTION_HIDE_APP_DISAMBIG_NONE_FEATURED);
Adam Powell2ed547e2015-04-29 18:45:04 -07001014 finish();
1015 }
Mike Lockwood02eb8742011-02-27 09:10:37 -08001016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017
Adam Powelle49d9392014-07-17 18:45:19 -07001018 /**
1019 * Replace me in subclasses!
1020 */
arangelovb0802dc2019-10-18 18:03:44 +01001021 @Override // ResolverListCommunicator
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +00001022 public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
Adam Powelle49d9392014-07-17 18:45:19 -07001023 return defIntent;
1024 }
1025
arangelovb0802dc2019-10-18 18:03:44 +01001026 @Override // ResolverListCommunicator
arangelov1b11cc12020-04-27 17:23:04 +01001027 public final void onPostListReady(ResolverListAdapter listAdapter, boolean doPostProcessing,
1028 boolean rebuildCompleted) {
arangelov4d3be0b2020-04-23 18:54:15 +01001029 if (isAutolaunching()) {
arangelov7981b122020-01-16 10:58:27 +00001030 return;
arangelovcf268642020-01-15 15:09:51 +00001031 }
arangelov27b99742020-04-23 18:59:09 +01001032 if (isIntentPicker()) {
1033 ((ResolverMultiProfilePagerAdapter) mMultiProfilePagerAdapter)
1034 .setUseLayoutWithDefault(useLayoutWithDefault());
1035 }
arangelovce7d4a62020-04-01 13:26:51 +01001036 if (mMultiProfilePagerAdapter.shouldShowEmptyStateScreen(listAdapter)) {
arangelov27608552020-03-27 16:57:50 +00001037 mMultiProfilePagerAdapter.showEmptyResolverListEmptyState(listAdapter);
arangelov4c0513d2020-03-05 22:24:13 +00001038 } else {
1039 mMultiProfilePagerAdapter.showListView(listAdapter);
arangelov590fba32020-02-11 18:05:42 +00001040 }
arangelov4d3be0b2020-04-23 18:54:15 +01001041 // showEmptyResolverListEmptyState can mark the tab as loaded,
1042 // which is a precondition for auto launching
arangelov1b11cc12020-04-27 17:23:04 +01001043 if (rebuildCompleted && maybeAutolaunchActivity()) {
arangelov4d3be0b2020-04-23 18:54:15 +01001044 return;
1045 }
arangelov7981b122020-01-16 10:58:27 +00001046 if (doPostProcessing) {
arangelov2c6115a2020-04-08 13:26:13 +01001047 maybeCreateHeader(listAdapter);
arangelov7981b122020-01-16 10:58:27 +00001048 resetButtonBar();
1049 onListRebuilt(listAdapter);
1050 }
arangelovb0802dc2019-10-18 18:03:44 +01001051 }
1052
arangelova3912cf2019-12-13 14:34:45 +00001053 protected void onListRebuilt(ResolverListAdapter listAdapter) {
arangelovcf268642020-01-15 15:09:51 +00001054 final ItemClickListener listener = new ItemClickListener();
1055 setupAdapterListView((ListView) mMultiProfilePagerAdapter.getActiveAdapterView(), listener);
arangelovbf806752020-04-09 18:31:50 +01001056 if (shouldShowTabs() && isIntentPicker()) {
1057 final ResolverDrawerLayout rdl = findViewById(R.id.contentPanel);
1058 if (rdl != null) {
1059 rdl.setMaxCollapsedHeight(getResources()
1060 .getDimensionPixelSize(useLayoutWithDefault()
1061 ? R.dimen.resolver_max_collapsed_height_with_default_with_tabs
1062 : R.dimen.resolver_max_collapsed_height_with_tabs));
1063 }
1064 }
arangelovb0802dc2019-10-18 18:03:44 +01001065 }
1066
Adam Powell2ed547e2015-04-29 18:45:04 -07001067 protected boolean onTargetSelected(TargetInfo target, boolean alwaysCheck) {
Adam Powell24428412015-04-01 17:19:56 -07001068 final ResolveInfo ri = target.getResolveInfo();
1069 final Intent intent = target != null ? target.getResolvedIntent() : null;
1070
arangelov38a6fce2019-12-02 18:21:22 +00001071 if (intent != null && (mSupportsAlwaysUseOption
arangelova3912cf2019-12-13 14:34:45 +00001072 || mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem())
1073 && mMultiProfilePagerAdapter.getActiveListAdapter().getUnfilteredResolveList() != null) {
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001074 // Build a reasonable intent filter, based on what matched.
1075 IntentFilter filter = new IntentFilter();
Henrik Engström3277cf12014-07-17 12:18:29 +02001076 Intent filterIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077
Henrik Engström3277cf12014-07-17 12:18:29 +02001078 if (intent.getSelector() != null) {
1079 filterIntent = intent.getSelector();
1080 } else {
1081 filterIntent = intent;
1082 }
1083
1084 String action = filterIntent.getAction();
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001085 if (action != null) {
1086 filter.addAction(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 }
Henrik Engström3277cf12014-07-17 12:18:29 +02001088 Set<String> categories = filterIntent.getCategories();
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001089 if (categories != null) {
1090 for (String cat : categories) {
1091 filter.addCategory(cat);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093 }
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001094 filter.addCategory(Intent.CATEGORY_DEFAULT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095
Adam Powell24428412015-04-01 17:19:56 -07001096 int cat = ri.match & IntentFilter.MATCH_CATEGORY_MASK;
Henrik Engström3277cf12014-07-17 12:18:29 +02001097 Uri data = filterIntent.getData();
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001098 if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
Henrik Engström3277cf12014-07-17 12:18:29 +02001099 String mimeType = filterIntent.resolveType(this);
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001100 if (mimeType != null) {
1101 try {
1102 filter.addDataType(mimeType);
1103 } catch (IntentFilter.MalformedMimeTypeException e) {
1104 Log.w("ResolverActivity", e);
1105 filter = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
1107 }
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001108 }
1109 if (data != null && data.getScheme() != null) {
1110 // We need the data specification if there was no type,
1111 // OR if the scheme is not one of our magical "file:"
1112 // or "content:" schemes (see IntentFilter for the reason).
1113 if (cat != IntentFilter.MATCH_CATEGORY_TYPE
1114 || (!"file".equals(data.getScheme())
1115 && !"content".equals(data.getScheme()))) {
1116 filter.addDataScheme(data.getScheme());
1117
1118 // Look through the resolved filter to determine which part
1119 // of it matched the original Intent.
1120 Iterator<PatternMatcher> pIt = ri.filter.schemeSpecificPartsIterator();
1121 if (pIt != null) {
1122 String ssp = data.getSchemeSpecificPart();
1123 while (ssp != null && pIt.hasNext()) {
1124 PatternMatcher p = pIt.next();
1125 if (p.match(ssp)) {
1126 filter.addDataSchemeSpecificPart(p.getPath(), p.getType());
1127 break;
1128 }
Dianne Hackborndf1c0bf2013-06-12 16:21:38 -07001129 }
1130 }
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001131 Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
1132 if (aIt != null) {
1133 while (aIt.hasNext()) {
1134 IntentFilter.AuthorityEntry a = aIt.next();
1135 if (a.match(data) >= 0) {
1136 int port = a.getPort();
1137 filter.addDataAuthority(a.getHost(),
1138 port >= 0 ? Integer.toString(port) : null);
1139 break;
1140 }
1141 }
1142 }
1143 pIt = ri.filter.pathsIterator();
1144 if (pIt != null) {
1145 String path = data.getPath();
1146 while (path != null && pIt.hasNext()) {
1147 PatternMatcher p = pIt.next();
1148 if (p.match(path)) {
1149 filter.addDataPath(p.getPath(), p.getType());
1150 break;
1151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
1153 }
1154 }
1155 }
1156
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001157 if (filter != null) {
arangelova3912cf2019-12-13 14:34:45 +00001158 final int N = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00001159 .getUnfilteredResolveList().size();
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001160 ComponentName[] set;
1161 // If we don't add back in the component for forwarding the intent to a managed
1162 // profile, the preferred activity may not be updated correctly (as the set of
1163 // components we tell it we knew about will have changed).
arangelovb0802dc2019-10-18 18:03:44 +01001164 final boolean needToAddBackProfileForwardingComponent =
arangelova3912cf2019-12-13 14:34:45 +00001165 mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile() != null;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001166 if (!needToAddBackProfileForwardingComponent) {
1167 set = new ComponentName[N];
1168 } else {
1169 set = new ComponentName[N + 1];
1170 }
1171
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001172 int bestMatch = 0;
1173 for (int i=0; i<N; i++) {
arangelova3912cf2019-12-13 14:34:45 +00001174 ResolveInfo r = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00001175 .getUnfilteredResolveList().get(i).getResolveInfoAt(0);
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001176 set[i] = new ComponentName(r.activityInfo.packageName,
1177 r.activityInfo.name);
1178 if (r.match > bestMatch) bestMatch = r.match;
1179 }
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001180
1181 if (needToAddBackProfileForwardingComponent) {
arangelova3912cf2019-12-13 14:34:45 +00001182 set[N] = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00001183 .getOtherProfile().getResolvedComponentName();
arangelova3912cf2019-12-13 14:34:45 +00001184 final int otherProfileMatch = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00001185 .getOtherProfile().getResolveInfo().match;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001186 if (otherProfileMatch > bestMatch) bestMatch = otherProfileMatch;
1187 }
1188
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001189 if (alwaysCheck) {
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001190 final int userId = getUserId();
1191 final PackageManager pm = getPackageManager();
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001192
1193 // Set the preferred Activity
1194 pm.addPreferredActivity(filter, bestMatch, set, intent.getComponent());
1195
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001196 if (ri.handleAllWebDataURI) {
1197 // Set default Browser if needed
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001198 final String packageName = pm.getDefaultBrowserPackageNameAsUser(userId);
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001199 if (TextUtils.isEmpty(packageName)) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001200 pm.setDefaultBrowserPackageNameAsUser(ri.activityInfo.packageName, userId);
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001201 }
1202 } else {
1203 // Update Domain Verification status
1204 ComponentName cn = intent.getComponent();
1205 String packageName = cn.getPackageName();
1206 String dataScheme = (data != null) ? data.getScheme() : null;
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001207
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001208 boolean isHttpOrHttps = (dataScheme != null) &&
1209 (dataScheme.equals(IntentFilter.SCHEME_HTTP) ||
1210 dataScheme.equals(IntentFilter.SCHEME_HTTPS));
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001211
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001212 boolean isViewAction = (action != null) && action.equals(Intent.ACTION_VIEW);
1213 boolean hasCategoryBrowsable = (categories != null) &&
1214 categories.contains(Intent.CATEGORY_BROWSABLE);
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001215
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001216 if (isHttpOrHttps && isViewAction && hasCategoryBrowsable) {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001217 pm.updateIntentVerificationStatusAsUser(packageName,
Fabrice Di Meglio3453e082015-05-11 17:46:23 -07001218 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
1219 userId);
1220 }
Fabrice Di Meglio1c1b4712014-11-19 17:12:32 -08001221 }
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001222 } else {
1223 try {
arangelova3912cf2019-12-13 14:34:45 +00001224 mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00001225 .mResolverListController.setLastChosen(intent, filter, bestMatch);
Amith Yamasani588dd2a2013-09-03 12:30:44 -07001226 } catch (RemoteException re) {
1227 Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
1228 }
Amith Yamasanie9ecc8b2013-08-22 11:16:27 -07001229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 }
1231 }
1232
Adam Powell24428412015-04-01 17:19:56 -07001233 if (target != null) {
arangelov9a8a6742020-06-01 14:17:32 +01001234 if (intent != null && isLaunchingTargetInOtherProfile()) {
1235 prepareIntentForCrossProfileLaunch(intent);
arangelov9e148522020-01-15 21:11:51 +00001236 }
Adam Powell24428412015-04-01 17:19:56 -07001237 safelyStartActivity(target);
Matt Pietala4b30072019-04-04 13:44:36 -04001238
1239 // Rely on the ActivityManager to pop up a dialog regarding app suspension
1240 // and return false
1241 if (target.isSuspended()) {
1242 return false;
1243 }
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001244 }
Matt Pietala4b30072019-04-04 13:44:36 -04001245
Adam Powell2ed547e2015-04-29 18:45:04 -07001246 return true;
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001247 }
1248
arangelov7c510c22020-06-03 18:24:40 +01001249 private void prepareIntentForCrossProfileLaunch(Intent intent) {
1250 intent.fixUris(UserHandle.myUserId());
1251 }
arangelov9a8a6742020-06-01 14:17:32 +01001252
1253 private boolean isLaunchingTargetInOtherProfile() {
1254 return mMultiProfilePagerAdapter.getCurrentUserHandle().getIdentifier()
1255 != UserHandle.myUserId();
1256 }
1257
arangelovcf268642020-01-15 15:09:51 +00001258 @VisibleForTesting
Adam Powell23882512016-01-29 10:21:00 -08001259 public void safelyStartActivity(TargetInfo cti) {
Jeff Sharkey2b9eb892016-02-16 09:21:51 -07001260 // We're dispatching intents that might be coming from legacy apps, so
1261 // don't kill ourselves.
1262 StrictMode.disableDeathOnFileUriExposure();
1263 try {
1264 safelyStartActivityInternal(cti);
1265 } finally {
1266 StrictMode.enableDeathOnFileUriExposure();
1267 }
1268 }
1269
1270 private void safelyStartActivityInternal(TargetInfo cti) {
arangelov96dec882020-01-31 20:23:40 +00001271 if (mPersonalPackageMonitor != null) {
1272 mPersonalPackageMonitor.unregister();
1273 }
arangelov7981b122020-01-16 10:58:27 +00001274 if (mWorkPackageMonitor != null) {
1275 mWorkPackageMonitor.unregister();
1276 }
1277 mRegistered = false;
Sander Alewijnsef6545332014-10-31 12:39:02 +00001278 // If needed, show that intent is forwarded
1279 // from managed profile to owner or other way around.
1280 if (mProfileSwitchMessageId != -1) {
1281 Toast.makeText(this, getString(mProfileSwitchMessageId), Toast.LENGTH_LONG).show();
1282 }
arangelov38a6fce2019-12-02 18:21:22 +00001283 UserHandle currentUserHandle = mMultiProfilePagerAdapter.getCurrentUserHandle();
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001284 if (!mSafeForwardingMode) {
arangelov38a6fce2019-12-02 18:21:22 +00001285 if (cti.startAsUser(this, null, currentUserHandle)) {
Adam Powell24428412015-04-01 17:19:56 -07001286 onActivityStarted(cti);
arangelov4bf17472020-02-17 20:21:46 +00001287 maybeLogCrossProfileTargetLaunch(cti, currentUserHandle);
Adam Powell24428412015-04-01 17:19:56 -07001288 }
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001289 return;
1290 }
1291 try {
arangelov38a6fce2019-12-02 18:21:22 +00001292 if (cti.startAsCaller(this, null, currentUserHandle.getIdentifier())) {
Adam Powell24428412015-04-01 17:19:56 -07001293 onActivityStarted(cti);
arangelov4bf17472020-02-17 20:21:46 +00001294 maybeLogCrossProfileTargetLaunch(cti, currentUserHandle);
Adam Powell24428412015-04-01 17:19:56 -07001295 }
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001296 } catch (RuntimeException e) {
1297 String launchedFromPackage;
1298 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 launchedFromPackage = ActivityTaskManager.getService().getLaunchedFromPackage(
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001300 getActivityToken());
1301 } catch (RemoteException e2) {
1302 launchedFromPackage = "??";
1303 }
1304 Slog.wtf(TAG, "Unable to launch as uid " + mLaunchedFromUid
1305 + " package " + launchedFromPackage + ", while running in "
1306 + ActivityThread.currentProcessName(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309
arangelov4bf17472020-02-17 20:21:46 +00001310 private void maybeLogCrossProfileTargetLaunch(TargetInfo cti, UserHandle currentUserHandle) {
arangelove5b369c2020-03-12 17:36:05 +00001311 if (!hasWorkProfile() || currentUserHandle.equals(getUser())) {
arangelov4bf17472020-02-17 20:21:46 +00001312 return;
1313 }
1314 DevicePolicyEventLogger
1315 .createEvent(DevicePolicyEnums.RESOLVER_CROSS_PROFILE_TARGET_OPENED)
arangelove5b369c2020-03-12 17:36:05 +00001316 .setBoolean(currentUserHandle.equals(getPersonalProfileUserHandle()))
arangelov4bf17472020-02-17 20:21:46 +00001317 .setStrings(getMetricsCategory(),
1318 cti instanceof ChooserTargetInfo ? "direct_share" : "other_target")
1319 .write();
1320 }
1321
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322
arangelovb0802dc2019-10-18 18:03:44 +01001323 public boolean startAsCallerImpl(Intent intent, Bundle options, boolean ignoreTargetSecurity,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001324 int userId) {
1325 // Pass intent to delegate chooser activity with permission token.
1326 // TODO: This should move to a trampoline Activity in the system when the ChooserActivity
1327 // moves into systemui
1328 try {
1329 // TODO: Once this is a small springboard activity, it can move off the UI process
1330 // and we can move the request method to ActivityManagerInternal.
1331 IBinder permissionToken = ActivityTaskManager.getService()
1332 .requestStartActivityPermissionToken(getActivityToken());
1333 final Intent chooserIntent = new Intent();
1334 final ComponentName delegateActivity = ComponentName.unflattenFromString(
1335 Resources.getSystem().getString(R.string.config_chooserActivity));
1336 chooserIntent.setClassName(delegateActivity.getPackageName(),
1337 delegateActivity.getClassName());
1338 chooserIntent.putExtra(ActivityTaskManager.EXTRA_PERMISSION_TOKEN, permissionToken);
1339
1340 // TODO: These extras will change as chooser activity moves into systemui
1341 chooserIntent.putExtra(Intent.EXTRA_INTENT, intent);
1342 chooserIntent.putExtra(ActivityTaskManager.EXTRA_OPTIONS, options);
1343 chooserIntent.putExtra(ActivityTaskManager.EXTRA_IGNORE_TARGET_SECURITY,
1344 ignoreTargetSecurity);
1345 chooserIntent.putExtra(Intent.EXTRA_USER_ID, userId);
Alison Cichowlas7b6f3b62018-12-07 09:06:57 -05001346 chooserIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
1347 | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001348 startActivity(chooserIntent);
1349 } catch (RemoteException e) {
1350 Log.e(TAG, e.toString());
1351 }
1352 return true;
1353 }
1354
Adam Powell23882512016-01-29 10:21:00 -08001355 public void onActivityStarted(TargetInfo cti) {
Adam Powell0b3c1122014-10-09 12:50:14 -07001356 // Do nothing
1357 }
1358
arangelovb0802dc2019-10-18 18:03:44 +01001359 @Override // ResolverListCommunicator
Adam Powell23882512016-01-29 10:21:00 -08001360 public boolean shouldGetActivityMetadata() {
Adam Powell24428412015-04-01 17:19:56 -07001361 return false;
1362 }
1363
Adam Powell23882512016-01-29 10:21:00 -08001364 public boolean shouldAutoLaunchSingleChoice(TargetInfo target) {
Matt Pietala4b30072019-04-04 13:44:36 -04001365 return !target.isSuspended();
Adam Powell39e94eb2015-09-08 17:01:49 -07001366 }
1367
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001368 void showTargetDetails(ResolveInfo ri) {
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07001369 Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
Adam Powell0fc5b2b2012-07-18 18:20:29 -07001370 .setData(Uri.fromParts("package", ri.activityInfo.packageName, null))
Adam Powell24428412015-04-01 17:19:56 -07001371 .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
arangelovebf3c052020-03-17 13:11:37 +00001372 startActivityAsUser(in, mMultiProfilePagerAdapter.getCurrentUserHandle());
Adam Powellc5878612012-05-04 18:42:38 -07001373 }
1374
arangelov38a6fce2019-12-02 18:21:22 +00001375 @VisibleForTesting
1376 protected ResolverListAdapter createResolverListAdapter(Context context,
1377 List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
Narayan Kamath75418682020-05-07 13:42:05 +01001378 boolean filterLastUsed, UserHandle userHandle) {
Paul McLean07425c82019-10-18 12:00:11 -06001379 Intent startIntent = getIntent();
1380 boolean isAudioCaptureDevice =
1381 startIntent.getBooleanExtra(EXTRA_IS_AUDIO_CAPTURE_DEVICE, false);
arangelovb0802dc2019-10-18 18:03:44 +01001382 return new ResolverListAdapter(context, payloadIntents, initialIntents, rList,
Narayan Kamath75418682020-05-07 13:42:05 +01001383 filterLastUsed, createListController(userHandle), this,
Paul McLean07425c82019-10-18 12:00:11 -06001384 isAudioCaptureDevice);
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001385 }
1386
1387 @VisibleForTesting
arangelov38a6fce2019-12-02 18:21:22 +00001388 protected ResolverListController createListController(UserHandle userHandle) {
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001389 return new ResolverListController(
1390 this,
1391 mPm,
1392 getTargetIntent(),
1393 getReferrerPackageName(),
arangelov38a6fce2019-12-02 18:21:22 +00001394 mLaunchedFromUid,
1395 userHandle);
Adam Powell88831a22014-11-20 18:17:00 -08001396 }
1397
Adam Powell39e94eb2015-09-08 17:01:49 -07001398 /**
arangelovb0802dc2019-10-18 18:03:44 +01001399 * Sets up the content view.
arangelovbb572332019-11-13 12:50:08 +00001400 * @return <code>true</code> if the activity is finishing and creation should halt.
Adam Powell39e94eb2015-09-08 17:01:49 -07001401 */
arangelovbb572332019-11-13 12:50:08 +00001402 private boolean configureContentView() {
arangelova3912cf2019-12-13 14:34:45 +00001403 if (mMultiProfilePagerAdapter.getActiveListAdapter() == null) {
1404 throw new IllegalStateException("mMultiProfilePagerAdapter.getCurrentListAdapter() "
1405 + "cannot be null.");
arangelovb0802dc2019-10-18 18:03:44 +01001406 }
arangelov7981b122020-01-16 10:58:27 +00001407 // We partially rebuild the inactive adapter to determine if we should auto launch
arangelovb91d08f2020-03-05 21:50:14 +00001408 // isTabLoaded will be true here if the empty state screen is shown instead of the list.
1409 boolean rebuildCompleted = mMultiProfilePagerAdapter.rebuildActiveTab(true)
1410 || mMultiProfilePagerAdapter.getActiveListAdapter().isTabLoaded();
arangelov2a4d0b12020-03-04 18:15:04 +00001411 if (shouldShowTabs()) {
arangelovb91d08f2020-03-05 21:50:14 +00001412 boolean rebuildInactiveCompleted = mMultiProfilePagerAdapter.rebuildInactiveTab(false)
1413 || mMultiProfilePagerAdapter.getInactiveListAdapter().isTabLoaded();
arangelovdb0c1f12020-02-14 17:35:12 +00001414 rebuildCompleted = rebuildCompleted && rebuildInactiveCompleted;
1415 }
arangelov7981b122020-01-16 10:58:27 +00001416
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001417 if (useLayoutWithDefault()) {
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001418 mLayoutId = R.layout.resolver_list_with_default;
Adam Powell7d758002015-05-06 17:49:36 -07001419 } else {
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001420 mLayoutId = getLayoutResource();
Adam Powell7d758002015-05-06 17:49:36 -07001421 }
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001422 setContentView(mLayoutId);
arangelov38a6fce2019-12-02 18:21:22 +00001423 mMultiProfilePagerAdapter.setupViewPager(findViewById(R.id.profile_pager));
arangelovdb0c1f12020-02-14 17:35:12 +00001424 return postRebuildList(rebuildCompleted);
arangelovb0802dc2019-10-18 18:03:44 +01001425 }
Adam Powell7d758002015-05-06 17:49:36 -07001426
arangelovb0802dc2019-10-18 18:03:44 +01001427 /**
arangelovbb572332019-11-13 12:50:08 +00001428 * Finishing procedures to be performed after the list has been rebuilt.
1429 * </p>Subclasses must call postRebuildListInternal at the end of postRebuildList.
1430 * @param rebuildCompleted
1431 * @return <code>true</code> if the activity is finishing and creation should halt.
arangelovb0802dc2019-10-18 18:03:44 +01001432 */
arangelovbb572332019-11-13 12:50:08 +00001433 protected boolean postRebuildList(boolean rebuildCompleted) {
1434 return postRebuildListInternal(rebuildCompleted);
arangelovb0802dc2019-10-18 18:03:44 +01001435 }
1436
1437 /**
arangelovbb572332019-11-13 12:50:08 +00001438 * Finishing procedures to be performed after the list has been rebuilt.
1439 * @param rebuildCompleted
1440 * @return <code>true</code> if the activity is finishing and creation should halt.
arangelovb0802dc2019-10-18 18:03:44 +01001441 */
arangelovbb572332019-11-13 12:50:08 +00001442 final boolean postRebuildListInternal(boolean rebuildCompleted) {
arangelova3912cf2019-12-13 14:34:45 +00001443 int count = mMultiProfilePagerAdapter.getActiveListAdapter().getUnfilteredCount();
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001444
1445 // We only rebuild asynchronously when we have multiple elements to sort. In the case where
1446 // we're already done, we can check if we should auto-launch immediately.
arangelov7981b122020-01-16 10:58:27 +00001447 if (rebuildCompleted && maybeAutolaunchActivity()) {
1448 return true;
Jeff Sharkeycc2ae6b42015-09-29 13:04:46 -07001449 }
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001450
arangelovcf268642020-01-15 15:09:51 +00001451 setupViewVisibilities();
1452
arangelovf163a882020-02-18 17:18:47 +00001453 if (shouldShowTabs()) {
arangelovcf268642020-01-15 15:09:51 +00001454 setupProfileTabs();
1455 }
1456
arangelov38a6fce2019-12-02 18:21:22 +00001457 return false;
1458 }
1459
arangelov7981b122020-01-16 10:58:27 +00001460 private int isPermissionGranted(String permission, int uid) {
1461 return ActivityManager.checkComponentPermission(permission, uid,
1462 /* owningUid= */-1, /* exported= */ true);
1463 }
1464
1465 /**
1466 * @return {@code true} if a resolved target is autolaunched, otherwise {@code false}
1467 */
1468 private boolean maybeAutolaunchActivity() {
1469 int numberOfProfiles = mMultiProfilePagerAdapter.getItemCount();
1470 if (numberOfProfiles == 1 && maybeAutolaunchIfSingleTarget()) {
1471 return true;
arangelovf6986d42020-02-12 15:03:22 +00001472 } else if (numberOfProfiles == 2
arangelovb91d08f2020-03-05 21:50:14 +00001473 && mMultiProfilePagerAdapter.getActiveListAdapter().isTabLoaded()
1474 && mMultiProfilePagerAdapter.getInactiveListAdapter().isTabLoaded()
arangelovf6986d42020-02-12 15:03:22 +00001475 && (maybeAutolaunchIfNoAppsOnInactiveTab()
1476 || maybeAutolaunchIfCrossProfileSupported())) {
arangelov7981b122020-01-16 10:58:27 +00001477 return true;
1478 }
1479 return false;
1480 }
1481
1482 private boolean maybeAutolaunchIfSingleTarget() {
1483 int count = mMultiProfilePagerAdapter.getActiveListAdapter().getUnfilteredCount();
1484 if (count != 1) {
1485 return false;
1486 }
1487
arangelovdb0c1f12020-02-14 17:35:12 +00001488 if (mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile() != null) {
1489 return false;
1490 }
1491
arangelov7981b122020-01-16 10:58:27 +00001492 // Only one target, so we're a candidate to auto-launch!
1493 final TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter()
1494 .targetInfoForPosition(0, false);
1495 if (shouldAutoLaunchSingleChoice(target)) {
1496 safelyStartActivity(target);
1497 finish();
1498 return true;
1499 }
1500 return false;
1501 }
1502
arangelovf6986d42020-02-12 15:03:22 +00001503 private boolean maybeAutolaunchIfNoAppsOnInactiveTab() {
1504 int count = mMultiProfilePagerAdapter.getActiveListAdapter().getUnfilteredCount();
1505 if (count != 1) {
1506 return false;
1507 }
1508 ResolverListAdapter inactiveListAdapter =
1509 mMultiProfilePagerAdapter.getInactiveListAdapter();
1510 if (inactiveListAdapter.getUnfilteredCount() != 0) {
1511 return false;
1512 }
1513 TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter()
1514 .targetInfoForPosition(0, false);
1515 safelyStartActivity(target);
1516 finish();
1517 return true;
1518 }
1519
arangelov7981b122020-01-16 10:58:27 +00001520 /**
1521 * When we have a personal and a work profile, we auto launch in the following scenario:
1522 * - There is 1 resolved target on each profile
1523 * - That target is the same app on both profiles
1524 * - The target app has permission to communicate cross profiles
1525 * - The target app has declared it supports cross-profile communication via manifest metadata
1526 */
1527 private boolean maybeAutolaunchIfCrossProfileSupported() {
arangelov4bf17472020-02-17 20:21:46 +00001528 ResolverListAdapter activeListAdapter = mMultiProfilePagerAdapter.getActiveListAdapter();
1529 int count = activeListAdapter.getUnfilteredCount();
arangelov7981b122020-01-16 10:58:27 +00001530 if (count != 1) {
1531 return false;
1532 }
1533 ResolverListAdapter inactiveListAdapter =
1534 mMultiProfilePagerAdapter.getInactiveListAdapter();
1535 if (inactiveListAdapter.getUnfilteredCount() != 1) {
1536 return false;
1537 }
arangelov4bf17472020-02-17 20:21:46 +00001538 TargetInfo activeProfileTarget = activeListAdapter
arangelov7981b122020-01-16 10:58:27 +00001539 .targetInfoForPosition(0, false);
1540 TargetInfo inactiveProfileTarget = inactiveListAdapter.targetInfoForPosition(0, false);
1541 if (!Objects.equals(activeProfileTarget.getResolvedComponentName(),
1542 inactiveProfileTarget.getResolvedComponentName())) {
1543 return false;
1544 }
1545 if (!shouldAutoLaunchSingleChoice(activeProfileTarget)) {
1546 return false;
1547 }
1548 String packageName = activeProfileTarget.getResolvedComponentName().getPackageName();
1549 if (!canAppInteractCrossProfiles(packageName)) {
1550 return false;
1551 }
1552
arangelov4bf17472020-02-17 20:21:46 +00001553 DevicePolicyEventLogger
1554 .createEvent(DevicePolicyEnums.RESOLVER_AUTOLAUNCH_CROSS_PROFILE_TARGET)
arangelove5b369c2020-03-12 17:36:05 +00001555 .setBoolean(activeListAdapter.getUserHandle()
1556 .equals(getPersonalProfileUserHandle()))
arangelov4bf17472020-02-17 20:21:46 +00001557 .setStrings(getMetricsCategory())
1558 .write();
arangelov7981b122020-01-16 10:58:27 +00001559 safelyStartActivity(activeProfileTarget);
1560 finish();
1561 return true;
1562 }
1563
1564 /**
1565 * Returns whether the package has the necessary permissions to interact across profiles on
1566 * behalf of a given user.
1567 *
1568 * <p>This means meeting the following condition:
1569 * <ul>
1570 * <li>The app's {@link ApplicationInfo#crossProfile} flag must be true, and at least
1571 * one of the following conditions must be fulfilled</li>
1572 * <li>{@code Manifest.permission.INTERACT_ACROSS_USERS_FULL} granted.</li>
1573 * <li>{@code Manifest.permission.INTERACT_ACROSS_USERS} granted.</li>
1574 * <li>{@code Manifest.permission.INTERACT_ACROSS_PROFILES} granted, or the corresponding
1575 * AppOps {@code android:interact_across_profiles} is set to "allow".</li>
1576 * </ul>
1577 *
1578 */
1579 private boolean canAppInteractCrossProfiles(String packageName) {
1580 ApplicationInfo applicationInfo;
1581 try {
1582 applicationInfo = getPackageManager().getApplicationInfo(packageName, 0);
1583 } catch (NameNotFoundException e) {
1584 Log.e(TAG, "Package " + packageName + " does not exist on current user.");
1585 return false;
1586 }
1587 if (!applicationInfo.crossProfile) {
1588 return false;
1589 }
1590
1591 int packageUid = applicationInfo.uid;
1592
1593 if (isPermissionGranted(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1594 packageUid) == PackageManager.PERMISSION_GRANTED) {
1595 return true;
1596 }
1597 if (isPermissionGranted(android.Manifest.permission.INTERACT_ACROSS_USERS, packageUid)
1598 == PackageManager.PERMISSION_GRANTED) {
1599 return true;
1600 }
1601 if (PermissionChecker.checkPermissionForPreflight(this, INTERACT_ACROSS_PROFILES,
1602 PID_UNKNOWN, packageUid, packageName) == PackageManager.PERMISSION_GRANTED) {
1603 return true;
1604 }
1605 return false;
1606 }
1607
1608 private boolean isAutolaunching() {
1609 return !mRegistered && isFinishing();
1610 }
1611
arangelovcf268642020-01-15 15:09:51 +00001612 private void setupProfileTabs() {
Alex Kershaw760754e2020-05-12 11:32:23 +01001613 maybeHideDivider();
arangelovcf268642020-01-15 15:09:51 +00001614 TabHost tabHost = findViewById(R.id.profile_tabhost);
1615 tabHost.setup();
1616 ViewPager viewPager = findViewById(R.id.profile_pager);
arangelov9d894142020-04-21 21:08:21 +01001617 viewPager.setSaveEnabled(false);
arangelovcf268642020-01-15 15:09:51 +00001618 TabHost.TabSpec tabSpec = tabHost.newTabSpec(TAB_TAG_PERSONAL)
1619 .setContent(R.id.profile_pager)
1620 .setIndicator(getString(R.string.resolver_personal_tab));
1621 tabHost.addTab(tabSpec);
1622
1623 tabSpec = tabHost.newTabSpec(TAB_TAG_WORK)
1624 .setContent(R.id.profile_pager)
1625 .setIndicator(getString(R.string.resolver_work_tab));
1626 tabHost.addTab(tabSpec);
1627
1628 TabWidget tabWidget = tabHost.getTabWidget();
1629 tabWidget.setVisibility(View.VISIBLE);
1630 resetTabsHeaderStyle(tabWidget);
1631 updateActiveTabStyle(tabHost);
1632
1633 tabHost.setOnTabChangedListener(tabId -> {
1634 resetTabsHeaderStyle(tabWidget);
1635 updateActiveTabStyle(tabHost);
1636 if (TAB_TAG_PERSONAL.equals(tabId)) {
1637 viewPager.setCurrentItem(0);
1638 } else {
1639 viewPager.setCurrentItem(1);
1640 }
1641 setupViewVisibilities();
Susi Kharraz-Postdde9c3a2020-03-03 07:55:40 -05001642 maybeLogProfileChange();
arangelov2b15d712020-04-22 14:54:31 +01001643 onProfileTabSelected();
arangelov4bf17472020-02-17 20:21:46 +00001644 DevicePolicyEventLogger
1645 .createEvent(DevicePolicyEnums.RESOLVER_SWITCH_TABS)
1646 .setInt(viewPager.getCurrentItem())
1647 .setStrings(getMetricsCategory())
1648 .write();
arangelovcf268642020-01-15 15:09:51 +00001649 });
1650
1651 viewPager.setVisibility(View.VISIBLE);
1652 tabHost.setCurrentTab(mMultiProfilePagerAdapter.getCurrentPage());
arangelov349af6a2020-03-05 11:53:40 +00001653 mMultiProfilePagerAdapter.setOnProfileSelectedListener(
arangelovd85a74a2020-06-02 11:50:19 +01001654 new AbstractMultiProfilePagerAdapter.OnProfileSelectedListener() {
1655 @Override
1656 public void onProfileSelected(int index) {
1657 tabHost.setCurrentTab(index);
1658 resetButtonBar();
1659 resetCheckedItem();
1660 }
1661
1662 @Override
1663 public void onProfilePageStateChanged(int state) {
1664 onHorizontalSwipeStateChanged(state);
1665 }
arangelov349af6a2020-03-05 11:53:40 +00001666 });
Kholoud Mohamed77bc0f12020-05-15 19:51:26 +01001667 mMultiProfilePagerAdapter.setOnSwitchOnWorkSelectedListener(
1668 () -> {
1669 final View workTab = tabHost.getTabWidget().getChildAt(1);
1670 workTab.setFocusable(true);
1671 workTab.setFocusableInTouchMode(true);
1672 workTab.requestFocus();
1673 });
arangelov934c64c2020-02-14 13:48:23 +00001674 findViewById(R.id.resolver_tab_divider).setVisibility(View.VISIBLE);
arangelovcf268642020-01-15 15:09:51 +00001675 }
1676
arangelovd85a74a2020-06-02 11:50:19 +01001677 void onHorizontalSwipeStateChanged(int state) {}
1678
Alex Kershaw760754e2020-05-12 11:32:23 +01001679 private void maybeHideDivider() {
1680 if (!isIntentPicker()) {
1681 return;
1682 }
1683 final View divider = findViewById(R.id.divider);
1684 if (divider == null) {
1685 return;
1686 }
1687 divider.setVisibility(View.GONE);
1688 }
1689
arangelov2b15d712020-04-22 14:54:31 +01001690 /**
1691 * Callback called when user changes the profile tab.
1692 * <p>This method is intended to be overridden by subclasses.
1693 */
1694 protected void onProfileTabSelected() { }
1695
arangelov349af6a2020-03-05 11:53:40 +00001696 private void resetCheckedItem() {
1697 if (!isIntentPicker()) {
1698 return;
1699 }
1700 mLastSelected = ListView.INVALID_POSITION;
1701 ListView inactiveListView = (ListView) mMultiProfilePagerAdapter.getInactiveAdapterView();
1702 if (inactiveListView.getCheckedItemCount() > 0) {
1703 inactiveListView.setItemChecked(inactiveListView.getCheckedItemPosition(), false);
1704 }
1705 }
1706
arangelovcf268642020-01-15 15:09:51 +00001707 private void resetTabsHeaderStyle(TabWidget tabWidget) {
arangelov791509d2020-03-20 13:01:53 +00001708 String workContentDescription = getString(R.string.resolver_work_tab_accessibility);
1709 String personalContentDescription = getString(R.string.resolver_personal_tab_accessibility);
arangelovcf268642020-01-15 15:09:51 +00001710 for (int i = 0; i < tabWidget.getChildCount(); i++) {
arangelov78fd3602020-02-28 15:21:20 +00001711 View tabView = tabWidget.getChildAt(i);
1712 TextView title = tabView.findViewById(android.R.id.title);
arangelov4b8ad342020-03-17 13:56:00 +00001713 title.setTextAppearance(android.R.style.TextAppearance_DeviceDefault_DialogWindowTitle);
1714 title.setTextColor(getAttrColor(this, android.R.attr.textColorTertiary));
1715 title.setTextSize(TypedValue.COMPLEX_UNIT_PX,
1716 getResources().getDimension(R.dimen.resolver_tab_text_size));
arangelov791509d2020-03-20 13:01:53 +00001717 if (title.getText().equals(getString(R.string.resolver_personal_tab))) {
1718 tabView.setContentDescription(personalContentDescription);
1719 } else if (title.getText().equals(getString(R.string.resolver_work_tab))) {
1720 tabView.setContentDescription(workContentDescription);
1721 }
arangelovcf268642020-01-15 15:09:51 +00001722 }
1723 }
1724
arangelov4b8ad342020-03-17 13:56:00 +00001725 private static int getAttrColor(Context context, int attr) {
1726 TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
1727 int colorAccent = ta.getColor(0, 0);
1728 ta.recycle();
1729 return colorAccent;
1730 }
1731
arangelovcf268642020-01-15 15:09:51 +00001732 private void updateActiveTabStyle(TabHost tabHost) {
1733 TextView title = tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
1734 .findViewById(android.R.id.title);
arangelov4b8ad342020-03-17 13:56:00 +00001735 title.setTextColor(getAttrColor(this, android.R.attr.colorAccent));
arangelovcf268642020-01-15 15:09:51 +00001736 }
1737
1738 private void setupViewVisibilities() {
arangelov590fba32020-02-11 18:05:42 +00001739 ResolverListAdapter activeListAdapter = mMultiProfilePagerAdapter.getActiveListAdapter();
arangelovce7d4a62020-04-01 13:26:51 +01001740 if (!mMultiProfilePagerAdapter.shouldShowEmptyStateScreen(activeListAdapter)) {
arangelov590fba32020-02-11 18:05:42 +00001741 addUseDifferentAppLabelIfNecessary(activeListAdapter);
Adam Powell7d758002015-05-06 17:49:36 -07001742 }
1743 }
1744
Zhen Zhangbde7b462019-11-11 11:49:33 -08001745 /**
arangelovcf268642020-01-15 15:09:51 +00001746 * Add a label to signify that the user can pick a different app.
Zhen Zhangbde7b462019-11-11 11:49:33 -08001747 * @param adapter The adapter used to provide data to item views.
Zhen Zhangbde7b462019-11-11 11:49:33 -08001748 */
arangelovcf268642020-01-15 15:09:51 +00001749 public void addUseDifferentAppLabelIfNecessary(ResolverListAdapter adapter) {
Adam Powell7d758002015-05-06 17:49:36 -07001750 final boolean useHeader = adapter.hasFilteredItem();
arangelovcf268642020-01-15 15:09:51 +00001751 if (useHeader) {
1752 FrameLayout stub = findViewById(R.id.stub);
1753 stub.setVisibility(View.VISIBLE);
1754 TextView textView = (TextView) LayoutInflater.from(this).inflate(
1755 R.layout.resolver_different_item_header, null, false);
arangelovf163a882020-02-18 17:18:47 +00001756 if (shouldShowTabs()) {
arangelovcf268642020-01-15 15:09:51 +00001757 textView.setGravity(Gravity.CENTER);
1758 }
1759 stub.addView(textView);
1760 }
1761 }
1762
1763 private void setupAdapterListView(ListView listView, ItemClickListener listener) {
arangelov38a6fce2019-12-02 18:21:22 +00001764 listView.setOnItemClickListener(listener);
1765 listView.setOnItemLongClickListener(listener);
Adam Powell7d758002015-05-06 17:49:36 -07001766
Narayan Kamath75418682020-05-07 13:42:05 +01001767 if (mSupportsAlwaysUseOption) {
Adam Powell7d758002015-05-06 17:49:36 -07001768 listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
1769 }
Adam Powell24428412015-04-01 17:19:56 -07001770 }
1771
Matt Pietal26038402019-01-08 07:29:34 -05001772 /**
1773 * Configure the area above the app selection list (title, content preview, etc).
1774 */
arangelov2c6115a2020-04-08 13:26:13 +01001775 private void maybeCreateHeader(ResolverListAdapter listAdapter) {
arangelov4e2951b2020-04-23 18:59:09 +01001776 if (mHeaderCreatorUser != null
1777 && !listAdapter.getUserHandle().equals(mHeaderCreatorUser)) {
arangelov2c6115a2020-04-08 13:26:13 +01001778 return;
1779 }
1780 if (!shouldShowTabs()
1781 && listAdapter.getCount() == 0 && listAdapter.getPlaceholderCount() == 0) {
Alan Viverette51efddb2017-04-05 10:00:01 -04001782 final TextView titleView = findViewById(R.id.title);
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001783 if (titleView != null) {
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08001784 titleView.setVisibility(View.GONE);
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001785 }
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08001786 }
1787
1788 CharSequence title = mTitle != null
1789 ? mTitle
shafik69df96322018-12-18 15:41:19 +00001790 : getTitleForAction(getTargetIntent(), mDefaultTitleResId);
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08001791
1792 if (!TextUtils.isEmpty(title)) {
Alan Viverette51efddb2017-04-05 10:00:01 -04001793 final TextView titleView = findViewById(R.id.title);
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08001794 if (titleView != null) {
1795 titleView.setText(title);
1796 }
1797 setTitle(title);
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001798 }
1799
Alan Viverette51efddb2017-04-05 10:00:01 -04001800 final ImageView iconView = findViewById(R.id.icon);
arangelovb0802dc2019-10-18 18:03:44 +01001801 if (iconView != null) {
arangelov2c6115a2020-04-08 13:26:13 +01001802 listAdapter.loadFilteredItemIconTaskAsync(iconView);
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001803 }
arangelov4e2951b2020-04-23 18:59:09 +01001804 mHeaderCreatorUser = listAdapter.getUserHandle();
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001805 }
1806
arangelov38a6fce2019-12-02 18:21:22 +00001807 protected void resetButtonBar() {
Narayan Kamath75418682020-05-07 13:42:05 +01001808 if (!mSupportsAlwaysUseOption) {
shafik69df96322018-12-18 15:41:19 +00001809 return;
1810 }
1811 final ViewGroup buttonLayout = findViewById(R.id.button_bar);
arangelov5ecac7a92020-04-20 21:22:25 +01001812 if (buttonLayout == null) {
shafik69df96322018-12-18 15:41:19 +00001813 Log.e(TAG, "Layout unexpectedly does not have a button bar");
arangelov5ecac7a92020-04-20 21:22:25 +01001814 return;
shafik69df96322018-12-18 15:41:19 +00001815 }
arangelov5ecac7a92020-04-20 21:22:25 +01001816 ResolverListAdapter activeListAdapter =
1817 mMultiProfilePagerAdapter.getActiveListAdapter();
1818 View buttonBarDivider = findViewById(R.id.resolver_button_bar_divider);
arangelov5d9ca172020-06-04 18:18:59 +01001819 if (!useLayoutWithDefault()) {
1820 int inset = mSystemWindowInsets != null ? mSystemWindowInsets.bottom : 0;
1821 buttonLayout.setPadding(buttonLayout.getPaddingLeft(), buttonLayout.getPaddingTop(),
1822 buttonLayout.getPaddingRight(), getResources().getDimensionPixelSize(
1823 R.dimen.resolver_button_bar_spacing) + inset);
1824 }
arangelov5ecac7a92020-04-20 21:22:25 +01001825 if (activeListAdapter.isTabLoaded()
arangelov4e2951b2020-04-23 18:59:09 +01001826 && mMultiProfilePagerAdapter.shouldShowEmptyStateScreen(activeListAdapter)
1827 && !useLayoutWithDefault()) {
arangelov5ecac7a92020-04-20 21:22:25 +01001828 buttonLayout.setVisibility(View.INVISIBLE);
arangelov4e2951b2020-04-23 18:59:09 +01001829 if (buttonBarDivider != null) {
1830 buttonBarDivider.setVisibility(View.INVISIBLE);
1831 }
arangelov27b99742020-04-23 18:59:09 +01001832 setButtonBarIgnoreOffset(/* ignoreOffset */ false);
arangelov5ecac7a92020-04-20 21:22:25 +01001833 return;
1834 }
arangelov4e2951b2020-04-23 18:59:09 +01001835 if (buttonBarDivider != null) {
1836 buttonBarDivider.setVisibility(View.VISIBLE);
1837 }
arangelov5ecac7a92020-04-20 21:22:25 +01001838 buttonLayout.setVisibility(View.VISIBLE);
arangelov27b99742020-04-23 18:59:09 +01001839 setButtonBarIgnoreOffset(/* ignoreOffset */ true);
arangelov5ecac7a92020-04-20 21:22:25 +01001840
arangelov5ecac7a92020-04-20 21:22:25 +01001841 mOnceButton = (Button) buttonLayout.findViewById(R.id.button_once);
1842 mAlwaysButton = (Button) buttonLayout.findViewById(R.id.button_always);
1843
1844 resetAlwaysOrOnceButtonBar();
shafik69df96322018-12-18 15:41:19 +00001845 }
1846
arangelov27b99742020-04-23 18:59:09 +01001847 /**
1848 * Updates the button bar container {@code ignoreOffset} layout param.
1849 * <p>Setting this to {@code true} means that the button bar will be glued to the bottom of
1850 * the screen.
1851 */
1852 private void setButtonBarIgnoreOffset(boolean ignoreOffset) {
1853 View buttonBarContainer = findViewById(R.id.button_bar_container);
1854 if (buttonBarContainer != null) {
1855 ResolverDrawerLayout.LayoutParams layoutParams =
1856 (ResolverDrawerLayout.LayoutParams) buttonBarContainer.getLayoutParams();
1857 layoutParams.ignoreOffset = ignoreOffset;
1858 buttonBarContainer.setLayoutParams(layoutParams);
1859 }
1860 }
1861
shafik69df96322018-12-18 15:41:19 +00001862 private void resetAlwaysOrOnceButtonBar() {
arangelov349af6a2020-03-05 11:53:40 +00001863 // Disable both buttons initially
1864 setAlwaysButtonEnabled(false, ListView.INVALID_POSITION, false);
1865 mOnceButton.setEnabled(false);
1866
arangelova3912cf2019-12-13 14:34:45 +00001867 int filteredPosition = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00001868 .getFilteredPosition();
1869 if (useLayoutWithDefault() && filteredPosition != ListView.INVALID_POSITION) {
1870 setAlwaysButtonEnabled(true, filteredPosition, false);
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001871 mOnceButton.setEnabled(true);
Sergey Troshin40e979e2019-12-30 17:29:50 +01001872 // Focus the button if we already have the default option
1873 mOnceButton.requestFocus();
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08001874 return;
1875 }
1876
1877 // When the items load in, if an item was already selected, enable the buttons
arangelovcf268642020-01-15 15:09:51 +00001878 ListView currentAdapterView = (ListView) mMultiProfilePagerAdapter.getActiveAdapterView();
arangelov38a6fce2019-12-02 18:21:22 +00001879 if (currentAdapterView != null
1880 && currentAdapterView.getCheckedItemPosition() != ListView.INVALID_POSITION) {
1881 setAlwaysButtonEnabled(true, currentAdapterView.getCheckedItemPosition(), true);
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08001882 mOnceButton.setEnabled(true);
Hakan Seyalioglu33550122017-01-06 19:54:43 -08001883 }
1884 }
1885
arangelovb0802dc2019-10-18 18:03:44 +01001886 @Override // ResolverListCommunicator
1887 public boolean useLayoutWithDefault() {
arangelovcf268642020-01-15 15:09:51 +00001888 // We only use the default app layout when the profile of the active user has a
1889 // filtered item. We always show the same default app even in the inactive user profile.
1890 boolean currentUserAdapterHasFilteredItem;
1891 if (mMultiProfilePagerAdapter.getCurrentUserHandle().getIdentifier()
1892 == UserHandle.myUserId()) {
1893 currentUserAdapterHasFilteredItem =
1894 mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem();
1895 } else {
1896 currentUserAdapterHasFilteredItem =
1897 mMultiProfilePagerAdapter.getInactiveListAdapter().hasFilteredItem();
1898 }
1899 return mSupportsAlwaysUseOption && currentUserAdapterHasFilteredItem;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001900 }
1901
Adam Powellc412be62015-06-24 13:54:10 -07001902 /**
Jorim Jaggif631ef72017-02-24 13:49:47 +01001903 * If {@code retainInOnStop} is set to true, we will not finish ourselves when onStop gets
1904 * called and we are launched in a new task.
1905 */
1906 protected void setRetainInOnStop(boolean retainInOnStop) {
1907 mRetainInOnStop = retainInOnStop;
1908 }
1909
1910 /**
Adam Powellc412be62015-06-24 13:54:10 -07001911 * Check a simple match for the component of two ResolveInfos.
1912 */
arangelovb0802dc2019-10-18 18:03:44 +01001913 @Override // ResolverListCommunicator
1914 public boolean resolveInfoMatch(ResolveInfo lhs, ResolveInfo rhs) {
Adam Powellc412be62015-06-24 13:54:10 -07001915 return lhs == null ? rhs == null
1916 : lhs.activityInfo == null ? rhs.activityInfo == null
1917 : Objects.equals(lhs.activityInfo.name, rhs.activityInfo.name)
1918 && Objects.equals(lhs.activityInfo.packageName, rhs.activityInfo.packageName);
1919 }
1920
arangelov4bf17472020-02-17 20:21:46 +00001921 protected String getMetricsCategory() {
1922 return METRICS_CATEGORY_RESOLVER;
1923 }
1924
arangelovb0802dc2019-10-18 18:03:44 +01001925 @Override // ResolverListCommunicator
arangelov7981b122020-01-16 10:58:27 +00001926 public void onHandlePackagesChanged(ResolverListAdapter listAdapter) {
1927 if (listAdapter == mMultiProfilePagerAdapter.getActiveListAdapter()) {
arangelove5b369c2020-03-12 17:36:05 +00001928 if (listAdapter.getUserHandle().equals(getWorkProfileUserHandle())
arangelov2dd9f7b2020-02-27 10:54:24 +00001929 && mMultiProfilePagerAdapter.isWaitingToEnableWorkProfile()) {
1930 // We have just turned on the work profile and entered the pass code to start it,
1931 // now we are waiting to receive the ACTION_USER_UNLOCKED broadcast. There is no
1932 // point in reloading the list now, since the work profile user is still
1933 // turning on.
1934 return;
1935 }
arangelov7981b122020-01-16 10:58:27 +00001936 boolean listRebuilt = mMultiProfilePagerAdapter.rebuildActiveTab(true);
1937 if (listRebuilt) {
1938 ResolverListAdapter activeListAdapter =
1939 mMultiProfilePagerAdapter.getActiveListAdapter();
1940 activeListAdapter.notifyDataSetChanged();
arangelov581a3c52020-06-17 13:43:20 +01001941 if (activeListAdapter.getCount() == 0 && !inactiveListAdapterHasItems()) {
arangelov7981b122020-01-16 10:58:27 +00001942 // We no longer have any items... just finish the activity.
1943 finish();
1944 }
1945 }
1946 } else {
1947 mMultiProfilePagerAdapter.clearInactiveProfileCache();
Zhen Zhang55d66aa2019-10-14 17:11:19 -07001948 }
Zhen Zhang55d66aa2019-10-14 17:11:19 -07001949 }
Alison Cichowlas1c8816c2019-04-03 17:43:22 -04001950
arangelov581a3c52020-06-17 13:43:20 +01001951 private boolean inactiveListAdapterHasItems() {
1952 if (!shouldShowTabs()) {
1953 return false;
1954 }
1955 return mMultiProfilePagerAdapter.getInactiveListAdapter().getCount() > 0;
1956 }
1957
arangelov7f8743d2020-02-13 20:34:30 +00001958 private BroadcastReceiver createWorkProfileStateReceiver() {
1959 return new BroadcastReceiver() {
1960 @Override
1961 public void onReceive(Context context, Intent intent) {
1962 String action = intent.getAction();
arangelov2dd9f7b2020-02-27 10:54:24 +00001963 if (!TextUtils.equals(action, Intent.ACTION_USER_UNLOCKED)
arangelov7f8743d2020-02-13 20:34:30 +00001964 && !TextUtils.equals(action, Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE)) {
1965 return;
1966 }
arangelov2dd9f7b2020-02-27 10:54:24 +00001967 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1968 if (TextUtils.equals(action, Intent.ACTION_USER_UNLOCKED)
1969 && userHandle != getWorkProfileUserHandle().getIdentifier()) {
1970 return;
1971 }
1972 if (TextUtils.equals(action, Intent.ACTION_USER_UNLOCKED)) {
1973 mMultiProfilePagerAdapter.markWorkProfileEnabledBroadcastReceived();
1974 }
arangelov7f8743d2020-02-13 20:34:30 +00001975 if (mMultiProfilePagerAdapter.getCurrentUserHandle()
arangelove5b369c2020-03-12 17:36:05 +00001976 .equals(getWorkProfileUserHandle())) {
arangelov7f8743d2020-02-13 20:34:30 +00001977 mMultiProfilePagerAdapter.rebuildActiveTab(true);
1978 } else {
1979 mMultiProfilePagerAdapter.clearInactiveProfileCache();
1980 }
1981 }
1982 };
1983 }
1984
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08001985 @VisibleForTesting
1986 public static final class ResolvedComponentInfo {
Adam Powell2ed547e2015-04-29 18:45:04 -07001987 public final ComponentName name;
1988 private final List<Intent> mIntents = new ArrayList<>();
1989 private final List<ResolveInfo> mResolveInfos = new ArrayList<>();
Alison Cichowlas1fd47152019-11-14 19:50:55 -05001990 private boolean mPinned;
Adam Powell2ed547e2015-04-29 18:45:04 -07001991
1992 public ResolvedComponentInfo(ComponentName name, Intent intent, ResolveInfo info) {
1993 this.name = name;
1994 add(intent, info);
1995 }
1996
1997 public void add(Intent intent, ResolveInfo info) {
1998 mIntents.add(intent);
1999 mResolveInfos.add(info);
2000 }
2001
2002 public int getCount() {
2003 return mIntents.size();
2004 }
2005
2006 public Intent getIntentAt(int index) {
2007 return index >= 0 ? mIntents.get(index) : null;
2008 }
2009
2010 public ResolveInfo getResolveInfoAt(int index) {
2011 return index >= 0 ? mResolveInfos.get(index) : null;
2012 }
2013
2014 public int findIntent(Intent intent) {
2015 for (int i = 0, N = mIntents.size(); i < N; i++) {
2016 if (intent.equals(mIntents.get(i))) {
2017 return i;
2018 }
2019 }
2020 return -1;
2021 }
2022
2023 public int findResolveInfo(ResolveInfo info) {
2024 for (int i = 0, N = mResolveInfos.size(); i < N; i++) {
2025 if (info.equals(mResolveInfos.get(i))) {
2026 return i;
2027 }
2028 }
2029 return -1;
2030 }
Alison Cichowlas1fd47152019-11-14 19:50:55 -05002031
2032 public boolean isPinned() {
2033 return mPinned;
2034 }
2035
2036 public void setPinned(boolean pinned) {
2037 mPinned = pinned;
2038 }
Adam Powell2ed547e2015-04-29 18:45:04 -07002039 }
2040
Adam Powell7d758002015-05-06 17:49:36 -07002041 class ItemClickListener implements AdapterView.OnItemClickListener,
2042 AdapterView.OnItemLongClickListener {
2043 @Override
2044 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2045 final ListView listView = parent instanceof ListView ? (ListView) parent : null;
2046 if (listView != null) {
2047 position -= listView.getHeaderViewsCount();
2048 }
2049 if (position < 0) {
2050 // Header views don't count.
2051 return;
2052 }
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08002053 // If we're still loading, we can't yet enable the buttons.
arangelova3912cf2019-12-13 14:34:45 +00002054 if (mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00002055 .resolveInfoForPosition(position, true) == null) {
Hakan Seyalioglu23f34652017-02-03 09:38:35 -08002056 return;
2057 }
arangelov38a6fce2019-12-02 18:21:22 +00002058 ListView currentAdapterView =
arangelovcf268642020-01-15 15:09:51 +00002059 (ListView) mMultiProfilePagerAdapter.getActiveAdapterView();
arangelov38a6fce2019-12-02 18:21:22 +00002060 final int checkedPos = currentAdapterView.getCheckedItemPosition();
Adam Powell7d758002015-05-06 17:49:36 -07002061 final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08002062 if (!useLayoutWithDefault()
Ruchi Kandoi65d76c12017-08-18 13:05:39 -07002063 && (!hasValidSelection || mLastSelected != checkedPos)
Matt Pietal0d6834a2019-06-27 13:27:52 -04002064 && mAlwaysButton != null) {
2065 setAlwaysButtonEnabled(hasValidSelection, checkedPos, true);
Adam Powell7d758002015-05-06 17:49:36 -07002066 mOnceButton.setEnabled(hasValidSelection);
2067 if (hasValidSelection) {
arangelov38a6fce2019-12-02 18:21:22 +00002068 currentAdapterView.smoothScrollToPosition(checkedPos);
Sergey Troshin40e979e2019-12-30 17:29:50 +01002069 mOnceButton.requestFocus();
Adam Powell7d758002015-05-06 17:49:36 -07002070 }
2071 mLastSelected = checkedPos;
2072 } else {
2073 startSelected(position, false, true);
2074 }
2075 }
Adam Powell2d809622012-03-22 15:24:43 -07002076
2077 @Override
2078 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Adam Powell7d758002015-05-06 17:49:36 -07002079 final ListView listView = parent instanceof ListView ? (ListView) parent : null;
2080 if (listView != null) {
2081 position -= listView.getHeaderViewsCount();
Adam Powell24428412015-04-01 17:19:56 -07002082 }
Adam Powellfd1e93d2014-09-07 16:52:22 -07002083 if (position < 0) {
2084 // Header views don't count.
2085 return false;
2086 }
arangelova3912cf2019-12-13 14:34:45 +00002087 ResolveInfo ri = mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00002088 .resolveInfoForPosition(position, true);
Adam Powell23882512016-01-29 10:21:00 -08002089 showTargetDetails(ri);
Adam Powell2d809622012-03-22 15:24:43 -07002090 return true;
2091 }
2092
2093 }
Adam Powell0256c6f2013-05-29 16:42:33 -07002094
Dianne Hackbornec452d92014-11-11 17:16:56 -08002095 static final boolean isSpecificUriMatch(int match) {
2096 match = match&IntentFilter.MATCH_CATEGORY_MASK;
2097 return match >= IntentFilter.MATCH_CATEGORY_HOST
2098 && match <= IntentFilter.MATCH_CATEGORY_PATH;
2099 }
2100
Adam Powell4c470d62015-06-19 17:46:17 -07002101 static class PickTargetOptionRequest extends PickOptionRequest {
2102 public PickTargetOptionRequest(@Nullable Prompt prompt, Option[] options,
2103 @Nullable Bundle extras) {
2104 super(prompt, options, extras);
2105 }
2106
2107 @Override
2108 public void onCancel() {
2109 super.onCancel();
2110 final ResolverActivity ra = (ResolverActivity) getActivity();
2111 if (ra != null) {
2112 ra.mPickOptionRequest = null;
2113 ra.finish();
2114 }
2115 }
2116
2117 @Override
2118 public void onPickOptionResult(boolean finished, Option[] selections, Bundle result) {
2119 super.onPickOptionResult(finished, selections, result);
2120 if (selections.length != 1) {
2121 // TODO In a better world we would filter the UI presented here and let the
2122 // user refine. Maybe later.
2123 return;
2124 }
2125
2126 final ResolverActivity ra = (ResolverActivity) getActivity();
2127 if (ra != null) {
arangelova3912cf2019-12-13 14:34:45 +00002128 final TargetInfo ti = ra.mMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00002129 .getItem(selections[0].getIndex());
Adam Powell4c470d62015-06-19 17:46:17 -07002130 if (ra.onTargetSelected(ti, false)) {
2131 ra.mPickOptionRequest = null;
2132 ra.finish();
2133 }
2134 }
2135 }
2136 }
Susi Kharraz-Postdde9c3a2020-03-03 07:55:40 -05002137
2138 protected void maybeLogProfileChange() {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139}