2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.settings;
19 import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
21 import android.accounts.Account;
22 import android.accounts.AccountManager;
23 import android.accounts.AuthenticatorDescription;
24 import android.annotation.Nullable;
25 import android.app.Activity;
26 import android.content.ComponentName;
27 import android.content.ContentResolver;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.pm.PackageManager;
31 import android.content.pm.ResolveInfo;
32 import android.content.pm.UserInfo;
33 import android.content.res.Resources;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.os.Environment;
37 import android.os.SystemProperties;
38 import android.os.UserHandle;
39 import android.os.UserManager;
40 import android.provider.Settings;
41 import android.support.annotation.VisibleForTesting;
42 import android.telephony.euicc.EuiccManager;
43 import android.text.TextUtils;
44 import android.util.Log;
45 import android.view.LayoutInflater;
46 import android.view.View;
47 import android.view.View.OnScrollChangeListener;
48 import android.view.ViewGroup;
49 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
50 import android.widget.Button;
51 import android.widget.CheckBox;
52 import android.widget.ImageView;
53 import android.widget.LinearLayout;
54 import android.widget.ScrollView;
55 import android.widget.TextView;
57 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
58 import com.android.settings.core.InstrumentedFragment;
59 import com.android.settings.core.SubSettingLauncher;
60 import com.android.settings.enterprise.ActionDisabledByAdminDialogHelper;
61 import com.android.settings.password.ChooseLockSettingsHelper;
62 import com.android.settings.password.ConfirmLockPattern;
63 import com.android.settingslib.RestrictedLockUtils;
65 import java.util.List;
68 * Confirm and execute a reset of the device to a clean "just out of the box"
69 * state. Multiple confirmations are required: first, a general "are you sure
70 * you want to do this?" prompt, followed by a keyguard pattern trace if the user
71 * has defined one, followed by a final strongly-worded "THIS WILL ERASE EVERYTHING
72 * ON THE PHONE" prompt. If at any time the phone is allowed to go to sleep, is
73 * locked, et cetera, then the confirmation sequence is abandoned.
75 * This is the initial screen.
77 public class MasterClear extends InstrumentedFragment implements OnGlobalLayoutListener {
78 private static final String TAG = "MasterClear";
80 @VisibleForTesting static final int KEYGUARD_REQUEST = 55;
81 @VisibleForTesting static final int CREDENTIAL_CONFIRM_REQUEST = 56;
83 private static final String KEY_SHOW_ESIM_RESET_CHECKBOX
84 = "masterclear.allow_retain_esim_profiles_after_fdr";
86 static final String ERASE_EXTERNAL_EXTRA = "erase_sd";
87 static final String ERASE_ESIMS_EXTRA = "erase_esim";
89 private View mContentView;
90 @VisibleForTesting Button mInitiateButton;
91 private View mExternalStorageContainer;
92 @VisibleForTesting CheckBox mExternalStorage;
93 private View mEsimStorageContainer;
94 @VisibleForTesting CheckBox mEsimStorage;
95 @VisibleForTesting ScrollView mScrollView;
98 public void onGlobalLayout() {
99 mInitiateButton.setEnabled(hasReachedBottom(mScrollView));
103 public void onCreate(@Nullable Bundle savedInstanceState) {
104 super.onCreate(savedInstanceState);
105 getActivity().setTitle(R.string.master_clear_short_title);
109 * Keyguard validation is run using the standard {@link ConfirmLockPattern}
110 * component as a subactivity
111 * @param request the request code to be returned once confirmation finishes
112 * @return true if confirmation launched
114 private boolean runKeyguardConfirmation(int request) {
115 Resources res = getActivity().getResources();
116 return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
117 request, res.getText(R.string.master_clear_short_title));
121 boolean isValidRequestCode(int requestCode) {
122 return !((requestCode != KEYGUARD_REQUEST) && (requestCode != CREDENTIAL_CONFIRM_REQUEST));
126 public void onActivityResult(int requestCode, int resultCode, Intent data) {
127 super.onActivityResult(requestCode, resultCode, data);
128 onActivityResultInternal(requestCode, resultCode, data);
132 * Internal method that allows easy testing without dealing with super references.
135 void onActivityResultInternal(int requestCode, int resultCode, Intent data) {
136 if (!isValidRequestCode(requestCode)) {
140 if (resultCode != Activity.RESULT_OK) {
141 establishInitialState();
145 Intent intent = null;
146 // If returning from a Keyguard request, try to show an account confirmation request if
148 if (CREDENTIAL_CONFIRM_REQUEST != requestCode
149 && (intent = getAccountConfirmationIntent()) != null) {
150 showAccountCredentialConfirmation(intent);
152 showFinalConfirmation();
157 void showFinalConfirmation() {
158 final Bundle args = new Bundle();
159 args.putBoolean(ERASE_EXTERNAL_EXTRA, mExternalStorage.isChecked());
160 args.putBoolean(ERASE_ESIMS_EXTRA, mEsimStorage.isChecked());
161 new SubSettingLauncher(getContext())
162 .setDestination(MasterClearConfirm.class.getName())
164 .setTitle(R.string.master_clear_confirm_title)
165 .setSourceMetricsCategory(getMetricsCategory())
170 void showAccountCredentialConfirmation(Intent intent) {
171 startActivityForResult(intent, CREDENTIAL_CONFIRM_REQUEST);
175 Intent getAccountConfirmationIntent() {
176 final Context context = getActivity();
177 final String accountType = context.getString(R.string.account_type);
178 final String packageName = context.getString(R.string.account_confirmation_package);
179 final String className = context.getString(R.string.account_confirmation_class);
180 if (TextUtils.isEmpty(accountType)
181 || TextUtils.isEmpty(packageName)
182 || TextUtils.isEmpty(className)) {
183 Log.i(TAG, "Resources not set for account confirmation.");
186 final AccountManager am = AccountManager.get(context);
187 Account[] accounts = am.getAccountsByType(accountType);
188 if (accounts != null && accounts.length > 0) {
189 final Intent requestAccountConfirmation = new Intent()
190 .setPackage(packageName)
191 .setComponent(new ComponentName(packageName, className));
192 // Check to make sure that the intent is supported.
193 final PackageManager pm = context.getPackageManager();
194 final ResolveInfo resolution = pm.resolveActivity(requestAccountConfirmation, 0);
195 if (resolution != null
196 && resolution.activityInfo != null
197 && packageName.equals(resolution.activityInfo.packageName)) {
198 // Note that we need to check the packagename to make sure that an Activity resolver
200 return requestAccountConfirmation;
202 Log.i(TAG, "Unable to resolve Activity: " + packageName + "/" + className);
205 Log.d(TAG, "No " + accountType + " accounts installed!");
211 * If the user clicks to begin the reset sequence, we next require a
212 * keyguard confirmation if the user has currently enabled one. If there
213 * is no keyguard available, we simply go to the final confirmation prompt.
215 * If the user is in demo mode, route to the demo mode app for confirmation.
218 protected final Button.OnClickListener mInitiateListener = new Button.OnClickListener() {
220 public void onClick(View view) {
221 final Context context = view.getContext();
222 if (Utils.isDemoUser(context)) {
223 final ComponentName componentName = Utils.getDeviceOwnerComponent(context);
224 if (componentName != null) {
225 final Intent requestFactoryReset = new Intent()
226 .setPackage(componentName.getPackageName())
227 .setAction(Intent.ACTION_FACTORY_RESET);
228 context.startActivity(requestFactoryReset);
233 if (runKeyguardConfirmation(KEYGUARD_REQUEST)) {
237 Intent intent = getAccountConfirmationIntent();
238 if (intent != null) {
239 showAccountCredentialConfirmation(intent);
241 showFinalConfirmation();
247 * In its initial state, the activity presents a button for the user to
248 * click in order to initiate a confirmation sequence. This method is
249 * called from various other points in the code to reset the activity to
252 * <p>Reinflating views from resources is expensive and prevents us from
253 * caching widget pointers, so we use a single-inflate pattern: we lazy-
254 * inflate each view, caching all of the widget pointers we'll need at the
255 * time, then simply reuse the inflated views directly whenever we need
256 * to change contents.
259 void establishInitialState() {
260 mInitiateButton = mContentView.findViewById(R.id.initiate_master_clear);
261 mInitiateButton.setOnClickListener(mInitiateListener);
262 mExternalStorageContainer = mContentView.findViewById(R.id.erase_external_container);
263 mExternalStorage = mContentView.findViewById(R.id.erase_external);
264 mEsimStorageContainer = mContentView.findViewById(R.id.erase_esim_container);
265 mEsimStorage = mContentView.findViewById(R.id.erase_esim);
266 if (mScrollView != null) {
267 mScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
269 mScrollView = mContentView.findViewById(R.id.master_clear_scrollview);
272 * If the external storage is emulated, it will be erased with a factory
273 * reset at any rate. There is no need to have a separate option until
274 * we have a factory reset that only erases some directories and not
275 * others. Likewise, if it's non-removable storage, it could potentially have been
276 * encrypted, and will also need to be wiped.
278 boolean isExtStorageEmulated = Environment.isExternalStorageEmulated();
279 if (isExtStorageEmulated
280 || (!Environment.isExternalStorageRemovable() && isExtStorageEncrypted())) {
281 mExternalStorageContainer.setVisibility(View.GONE);
283 final View externalOption = mContentView.findViewById(R.id.erase_external_option_text);
284 externalOption.setVisibility(View.GONE);
286 final View externalAlsoErased = mContentView.findViewById(R.id.also_erases_external);
287 externalAlsoErased.setVisibility(View.VISIBLE);
289 // If it's not emulated, it is on a separate partition but it means we're doing
290 // a force wipe due to encryption.
291 mExternalStorage.setChecked(!isExtStorageEmulated);
293 mExternalStorageContainer.setOnClickListener(new View.OnClickListener() {
296 public void onClick(View v) {
297 mExternalStorage.toggle();
302 if (showWipeEuicc()) {
303 if (showWipeEuiccCheckbox()) {
304 TextView title = mContentView.findViewById(R.id.erase_esim_title);
305 title.setText(R.string.erase_esim_storage);
306 mEsimStorageContainer.setVisibility(View.VISIBLE);
307 mEsimStorageContainer.setOnClickListener(new View.OnClickListener() {
309 public void onClick(View v) {
310 mEsimStorage.toggle();
314 final View esimAlsoErased = mContentView.findViewById(R.id.also_erases_esim);
315 esimAlsoErased.setVisibility(View.VISIBLE);
317 final View noCancelMobilePlan = mContentView.findViewById(
318 R.id.no_cancel_mobile_plan);
319 noCancelMobilePlan.setVisibility(View.VISIBLE);
320 mEsimStorage.setChecked(true /* checked */);
324 final UserManager um = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
326 final StringBuffer contentDescription = new StringBuffer();
327 final View masterClearContainer = mContentView.findViewById(R.id.master_clear_container);
328 getContentDescription(masterClearContainer, contentDescription);
329 masterClearContainer.setContentDescription(contentDescription);
331 // Set the status of initiateButton based on scrollview
332 mScrollView.setOnScrollChangeListener(new OnScrollChangeListener() {
334 public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX,
336 if (v instanceof ScrollView && hasReachedBottom((ScrollView) v)) {
337 mInitiateButton.setEnabled(true);
338 mScrollView.setOnScrollChangeListener(null);
343 // Set the initial state of the initiateButton
344 mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(this);
348 * Whether to show strings indicating that the eUICC will be wiped.
350 * <p>We show the strings on any device which supports eUICC as long as the eUICC was ever
351 * provisioned (that is, at least one profile was ever downloaded onto it).
354 boolean showWipeEuicc() {
355 Context context = getContext();
356 if (!isEuiccEnabled(context)) {
359 ContentResolver cr = context.getContentResolver();
360 return Settings.Global.getInt(cr, Settings.Global.EUICC_PROVISIONED, 0) != 0
361 || Settings.Global.getInt(
362 cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
366 boolean showWipeEuiccCheckbox() {
367 return SystemProperties
368 .getBoolean(KEY_SHOW_ESIM_RESET_CHECKBOX, false /* def */);
372 protected boolean isEuiccEnabled(Context context) {
373 EuiccManager euiccManager = (EuiccManager) context.getSystemService(Context.EUICC_SERVICE);
374 return euiccManager.isEnabled();
378 boolean hasReachedBottom(final ScrollView scrollView) {
379 if (scrollView.getChildCount() < 1) {
383 final View view = scrollView.getChildAt(0);
384 final int diff = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY());
389 private void getContentDescription(View v, StringBuffer description) {
390 if (v.getVisibility() != View.VISIBLE) {
393 if (v instanceof ViewGroup) {
394 ViewGroup vGroup = (ViewGroup) v;
395 for (int i = 0; i < vGroup.getChildCount(); i++) {
396 View nextChild = vGroup.getChildAt(i);
397 getContentDescription(nextChild, description);
399 } else if (v instanceof TextView) {
400 TextView vText = (TextView) v;
401 description.append(vText.getText());
402 description.append(","); // Allow Talkback to pause between sections.
406 private boolean isExtStorageEncrypted() {
407 String state = SystemProperties.get("vold.decrypt");
408 return !"".equals(state);
411 private void loadAccountList(final UserManager um) {
412 View accountsLabel = mContentView.findViewById(R.id.accounts_label);
413 LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts);
414 contents.removeAllViews();
416 Context context = getActivity();
417 final List<UserInfo> profiles = um.getProfiles(UserHandle.myUserId());
418 final int profilesSize = profiles.size();
420 AccountManager mgr = AccountManager.get(context);
422 LayoutInflater inflater = (LayoutInflater)context.getSystemService(
423 Context.LAYOUT_INFLATER_SERVICE);
425 int accountsCount = 0;
426 for (int profileIndex = 0; profileIndex < profilesSize; profileIndex++) {
427 final UserInfo userInfo = profiles.get(profileIndex);
428 final int profileId = userInfo.id;
429 final UserHandle userHandle = new UserHandle(profileId);
430 Account[] accounts = mgr.getAccountsAsUser(profileId);
431 final int N = accounts.length;
437 AuthenticatorDescription[] descs = AccountManager.get(context)
438 .getAuthenticatorTypesAsUser(profileId);
439 final int M = descs.length;
441 if (profilesSize > 1) {
442 View titleView = Utils.inflateCategoryHeader(inflater, contents);
443 final TextView titleText = (TextView) titleView.findViewById(android.R.id.title);
444 titleText.setText(userInfo.isManagedProfile() ? R.string.category_work
445 : R.string.category_personal);
446 contents.addView(titleView);
449 for (int i = 0; i < N; i++) {
450 Account account = accounts[i];
451 AuthenticatorDescription desc = null;
452 for (int j = 0; j < M; j++) {
453 if (account.type.equals(descs[j].type)) {
459 Log.w(TAG, "No descriptor for account name=" + account.name
460 + " type=" + account.type);
463 Drawable icon = null;
465 if (desc.iconId != 0) {
466 Context authContext = context.createPackageContextAsUser(desc.packageName,
468 icon = context.getPackageManager().getUserBadgedIcon(
469 authContext.getDrawable(desc.iconId), userHandle);
471 } catch (PackageManager.NameNotFoundException e) {
472 Log.w(TAG, "Bad package name for account type " + desc.type);
473 } catch (Resources.NotFoundException e) {
474 Log.w(TAG, "Invalid icon id for account type " + desc.type, e);
477 icon = context.getPackageManager().getDefaultActivityIcon();
480 View child = inflater.inflate(R.layout.master_clear_account, contents, false);
481 ((ImageView) child.findViewById(android.R.id.icon)).setImageDrawable(icon);
482 ((TextView) child.findViewById(android.R.id.title)).setText(account.name);
483 contents.addView(child);
487 if (accountsCount > 0) {
488 accountsLabel.setVisibility(View.VISIBLE);
489 contents.setVisibility(View.VISIBLE);
491 // Checking for all other users and their profiles if any.
492 View otherUsers = mContentView.findViewById(R.id.other_users_present);
493 final boolean hasOtherUsers = (um.getUserCount() - profilesSize) > 0;
494 otherUsers.setVisibility(hasOtherUsers ? View.VISIBLE : View.GONE);
498 public View onCreateView(LayoutInflater inflater, ViewGroup container,
499 Bundle savedInstanceState) {
500 final Context context = getContext();
501 final EnforcedAdmin admin = RestrictedLockUtils.checkIfRestrictionEnforced(context,
502 UserManager.DISALLOW_FACTORY_RESET, UserHandle.myUserId());
503 final UserManager um = UserManager.get(context);
504 final boolean disallow = !um.isAdminUser() || RestrictedLockUtils.hasBaseUserRestriction(
505 context, UserManager.DISALLOW_FACTORY_RESET, UserHandle.myUserId());
506 if (disallow && !Utils.isDemoUser(context)) {
507 return inflater.inflate(R.layout.master_clear_disallowed_screen, null);
508 } else if (admin != null) {
509 new ActionDisabledByAdminDialogHelper(getActivity())
510 .prepareDialogBuilder(UserManager.DISALLOW_FACTORY_RESET, admin)
511 .setOnDismissListener(__ -> getActivity().finish())
513 return new View(getContext());
516 mContentView = inflater.inflate(R.layout.master_clear, null);
518 establishInitialState();
523 public int getMetricsCategory() {
524 return MetricsEvent.MASTER_CLEAR;