Android源码笔记--恢复出厂设置

时间:2025-01-29 06:58:25

       最近在学习Android系统源码,这一节主要是了解恢复出厂设置。实现恢复出厂一般是通过发广播操作,如下:

//恢复出厂设置
Intent recovery = new Intent(".MASTER_CLEAR");
("android");
sendBroadcast(recovery);

清单文件需要加:
 1 android:shareUserId = ""  //表明系统应用
 2 <uses-permission android:name=".MASTER_CLEAR" />

它的主要流程如下:

1 点击按钮,系统发送恢复出厂设置广播
2 系统MasterClearReceiver接收广播,并进行android层的相关处理最后重启
3 在/cache/recovery/command文件中写入命令字段
4 重启系统,进入Recovery模式
5 根据/cache/recovery/command中的命令字段清楚用户数据
6 重新启动系统,恢复出厂完成

简单来看一下源码:

/frameworks/base/services/core/java/com/android/server/

public class MasterClearReceiver extends BroadcastReceiver {
    private static final String TAG = "MasterClear";
    private boolean mWipeExternalStorage;
    private boolean mWipeEsims;

    @Override
    public void onReceive(final Context context, final Intent intent) {
       ...

        final String factoryResetPackage = context
                .getString(.config_factoryResetPackage);
        if (Intent.ACTION_FACTORY_RESET.equals(())
                && !(factoryResetPackage)) {
            (factoryResetPackage).setComponent(null);
            (intent, );
            return;
        }

        final boolean shutdown = ("shutdown", false);
        final String reason = (Intent.EXTRA_REASON);
        mWipeExternalStorage = (Intent.EXTRA_WIPE_EXTERNAL_STORAGE, false);
        mWipeEsims = (Intent.EXTRA_WIPE_ESIMS, false);
        final boolean forceWipe = (Intent.EXTRA_FORCE_MASTER_CLEAR, false)
                || (Intent.EXTRA_FORCE_FACTORY_RESET, false);

        (TAG, "!!! FACTORY RESET !!!");
        // The reboot call is blocking, so we need to do it on another thread.
        Thread thr = new Thread("Reboot") {
            @Override
            public void run() {
                try {
                    RecoverySystem
                            .rebootWipeUserData(context, shutdown, reason, forceWipe, mWipeEsims);
                    (TAG, "Still running after master clear?!");
                } catch (IOException e) {
                    (TAG, "Can't perform master clear/factory reset", e);
                } catch (SecurityException e) {
                    (TAG, "Can't perform master clear/factory reset", e);
                }
            }
        };

        if (mWipeExternalStorage) {
            // thr will be started at the end of this task.
            new WipeDataTask(context, thr).execute();
        } else {
            ();
        }
    }

    private class WipeDataTask extends AsyncTask<Void, Void, Void> {
        private final Thread mChainedTask;
        private final Context mContext;
        private final ProgressDialog mProgressDialog;

        public WipeDataTask(Context context, Thread chainedTask) {
            mContext = context;
            mChainedTask = chainedTask;
            mProgressDialog = new ProgressDialog(context);
        }

        @Override
        protected void onPreExecute() {
            (true);
            ().setType(.TYPE_SYSTEM_ALERT);
            ((.progress_erasing));
            ();
        }

        @Override
        protected Void doInBackground(Void... params) {
            (TAG, "Wiping adoptable disks");
            if (mWipeExternalStorage) {
                StorageManager sm = (StorageManager) (
                        Context.STORAGE_SERVICE);
                ();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            ();
            ();
        }
    }
}
<receiver android:name=""
            android:permission=".MASTER_CLEAR">
            <intent-filter
                    android:priority="100" >
                <!-- For Checkin, Settings, etc.: action=FACTORY_RESET -->
                <action android:name=".FACTORY_RESET" />
                <!-- As above until all the references to the deprecated MASTER_CLEAR get updated to
                     FACTORY_RESET. -->
                <action android:name=".MASTER_CLEAR" />

                <!-- MCS always uses REMOTE_INTENT: category=MASTER_CLEAR -->
                <action android:name="." />
                <category android:name=".MASTER_CLEAR" />
            </intent-filter>
 </receiver>
 /frameworks/base/core/java/android/os/


public class RecoverySystem {
 
  private final IRecoverySystem mService;
  
   public RecoverySystem(IRecoverySystem service) {
        mService = service;
    }
 
public static void rebootWipeUserData(Context context, boolean shutdown, String reason,
            boolean force, boolean wipeEuicc) throws IOException {
        UserManager um = (UserManager) (Context.USER_SERVICE);
        if (!force && (UserManager.DISALLOW_FACTORY_RESET)) {
            throw new SecurityException("Wiping data is not allowed for this user.");
        }
        final ConditionVariable condition = new ConditionVariable();

        Intent intent = new Intent(".MASTER_CLEAR_NOTIFICATION");
        (Intent.FLAG_RECEIVER_FOREGROUND
                | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
        (intent, ,
                .MASTER_CLEAR,
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        ();
                    }
                }, null, 0, null, null);

        // Block until the ordered broadcast has completed.
        ();

        EuiccManager euiccManager = ();
        if (wipeEuicc) {
            wipeEuiccData(context, PACKAGE_NAME_EUICC_DATA_MANAGEMENT_CALLBACK);
        } else {
            removeEuiccInvisibleSubs(context, euiccManager);
        }

        String shutdownArg = null;
        if (shutdown) {
            shutdownArg = "--shutdown_after";
        }

        String reasonArg = null;
        if (!(reason)) {
            String timeStamp = ("yyyy-MM-ddTHH:mm:ssZ", ()).toString();
            reasonArg = "--reason=" + sanitizeArg(reason + "," + timeStamp);
        }

        final String localeArg = "--locale=" + ().toLanguageTag() ;
        bootCommand(context, shutdownArg, "--wipe_data", reasonArg, localeArg);
    }
 private static void bootCommand(Context context, String... args) throws IOException {
        //删除日志信息 
		LOG_FILE.delete();

        StringBuilder command = new StringBuilder();
        for (String arg : args) {
            if (!(arg)) {
                (arg);
                ("\n");
            }
        }

        // Write the command into BCB (bootloader control block) and boot from
        // there. Will not return unless failed.
		// 将命令写到bootloader control block 
        RecoverySystem rs = (RecoverySystem) (Context.RECOVERY_SERVICE);
        (());

        throw new IOException("Reboot failed (no permissions?)");
    }

	 // 通过Binder与RecoverySystemService对话以设置BCB
    private void rebootRecoveryWithCommand(String command) {
        try {
            (command);
        } catch (RemoteException ignored) {
        }
    }

来看一下服务端:

/frameworks/base/services/core/java/com/android/server/recoverysystem/

    @Override // Binder call
    public void rebootRecoveryWithCommand(String command) {
        if (DEBUG) (TAG, "rebootRecoveryWithCommand: [" + command + "]");
        synchronized (sRequestLock) {
            if (!setupOrClearBcb(true, command)) {
                return;
            }

            // 设置完CBC,调用电源管理重启系统,进入恢复模式
            PowerManager pm = ();
            (PowerManager.REBOOT_RECOVERY);
        }
    }

 private boolean setupOrClearBcb(boolean isSetup, String command) {
        (, null);

        final boolean available = checkAndWaitForUncryptService();
        if (!available) {
            (TAG, "uncrypt service is unavailable.");
            return false;
        }

        if (isSetup) {
            ("", "setup-bcb");
        } else {
            ("", "clear-bcb");
        }

        // Connect to the uncrypt service socket.
        UncryptSocket socket = ();
        if (socket == null) {
            (TAG, "Failed to connect to uncrypt socket");
            return false;
        }

        try {
            // Send the BCB commands if it's to setup BCB.
            if (isSetup) {
                (command);
            }

            // Read the status from the socket.
            int status = ();

            // Ack receipt of the status code. uncrypt waits for the ack so
            // the socket won't be destroyed before we receive the code.
            ();

            if (status == 100) {
                (TAG, "uncrypt " + (isSetup ? "setup" : "clear")
                        + " bcb successfully finished.");
            } else {
                // Error in /system/bin/uncrypt.
                (TAG, "uncrypt failed with status: " + status);
                return false;
            }
        } catch (IOException e) {
            (TAG, "IOException when communicating with uncrypt:", e);
            return false;
        } finally {
            ();
        }

        return true;
    }	
/frameworks/base/core/java/android/os/
public final class PowerManager {

  @UnsupportedAppUsage
    final IPowerManager mService;
	
	    /**
     * {@hide}
     */
    public PowerManager(Context context, IPowerManager service, IThermalService thermalService,
            Handler handler) {
        mContext = context;
        mService = service;
        mThermalService = thermalService;
        mHandler = handler;
    }

	   public void reboot(@Nullable String reason) {
        if (REBOOT_USERSPACE.equals(reason) && !isRebootingUserspaceSupported()) {
            throw new UnsupportedOperationException(
                    "Attempted userspace reboot on a device that doesn't support it");
        }
        try {
            (false, reason, true);
        } catch (RemoteException e) {
            throw ();
        }
    }
}
/frameworks/base/services/core/java/com/android/server/power/

 /**
         * Reboots the device.
         *
         * @param confirm If true, shows a reboot confirmation dialog.
         * @param reason The reason for the reboot, or null if none.
         * @param wait If true, this call waits for the reboot to complete and does not return.
         */
        @Override // Binder call
        public void reboot(boolean confirm, @Nullable String reason, boolean wait) {
            (, null);
            if (PowerManager.REBOOT_RECOVERY.equals(reason)
                    || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
                (, null);
            }

            final long ident = ();
            try {
                shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
            } finally {
                (ident);
            }
        }
	
	
	private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
            @Nullable final String reason, boolean wait) {
        if (PowerManager.REBOOT_USERSPACE.equals(reason)) {
            if (!()) {
                throw new UnsupportedOperationException(
                        "Attempted userspace reboot on a device that doesn't support it");
            }
            ();
        }
        if (mHandler == null || !mSystemReady) {
            if (()) {
                // If we're stuck in a really low-level reboot loop, and a
                // rescue party is trying to prompt the user for a factory data
                // reset, we must GET TO DA CHOPPA!
                (reason);
            } else {
                throw new IllegalStateException("Too early to call shutdown() or reboot()");
            }
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
                        (getUiContext(), confirm);
                    } else if (haltMode == HALT_MODE_REBOOT) {
                        (getUiContext(), reason, confirm);
                    } else {
                        (getUiContext(), reason, confirm);
                    }
                }
            }
        };

        // ShutdownThread must run on a looper capable of displaying the UI.
        Message msg = ((), runnable);
        (true);
        ().sendMessage(msg);

        // () is documented not to return so just wait for the inevitable.
        if (wait) {
            synchronized (runnable) {
                while (true) {
                    try {
                        ();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }
/frameworks/base/services/core/java/com/android/server/power/
	
	
	private static final ShutdownThread sInstance = new ShutdownThread();
	
	   public static void rebootSafeMode(final Context context, boolean confirm) {
        UserManager um = (UserManager) (Context.USER_SERVICE);
        if ((UserManager.DISALLOW_SAFE_BOOT)) {
            return;
        }

        mReboot = true;
        mRebootSafeMode = true;
        mRebootHasProgressBar = false;
        mReason = null;
        shutdownInner(context, confirm);
    }
	
	
	public static void reboot(final Context context, String reason, boolean confirm) {
        mReboot = true;
        mRebootSafeMode = false;
        mRebootHasProgressBar = false;
        mReason = reason;
        shutdownInner(context, confirm);
    }
	
	
	 public static void shutdown(final Context context, String reason, boolean confirm) {
        mReboot = false;
        mRebootSafeMode = false;
        mReason = reason;
        shutdownInner(context, confirm);
    }
	
	
	private static void shutdownInner(final Context context, boolean confirm) {
        // ShutdownThread is called from many places, so best to verify here that the context passed
        // in is themed.
        ();

        // ensure that only one thread is trying to power down.
        // any additional calls are just returned
        synchronized (sIsStartedGuard) {
            if (sIsStarted) {
                (TAG, "Request to shutdown already running, returning.");
                return;
            }
        }

        final int longPressBehavior = ().getInteger(
                        .config_longPressOnPowerBehavior);
        final int resourceId = mRebootSafeMode
                ? .reboot_safemode_confirm
                : (longPressBehavior == 2
                        ? .shutdown_confirm_question
                        : .shutdown_confirm);

        (TAG, "Notifying thread to start shutdown longPressBehavior=" + longPressBehavior);

        if (confirm) {
            final CloseDialogReceiver closer = new CloseDialogReceiver(context);
            if (sConfirmDialog != null) {
                ();
            }
            sConfirmDialog = new (context)
                    .setTitle(mRebootSafeMode
                            ? .reboot_safemode_title
                            : .power_off)
                    .setMessage(resourceId)
                    .setPositiveButton(, new () {
                        public void onClick(DialogInterface dialog, int which) {
                            beginShutdownSequence(context);
                        }
                    })
                    .setNegativeButton(, null)
                    .create();
             = sConfirmDialog;
            (closer);
            ().setType(.TYPE_KEYGUARD_DIALOG);
            ();
        } else {
            beginShutdownSequence(context);
        }
    }
/frameworks/base/core/java/android/os/storage/

 private final IStorageManager mStorageManager;
 
  @UnsupportedAppUsage
    public StorageManager(Context context, Looper looper) throws ServiceNotFoundException {
        mContext = context;
        mResolver = ();
        mLooper = looper;
        mStorageManager = (("mount"));
        mAppOps = ();
    }
	
 /** {@hide} */
    public void wipeAdoptableDisks() {
        // We only wipe devices in "adoptable" locations, which are in a
        // long-term stable slot/location on the device, where apps have a
        // reasonable chance of storing sensitive data. (Apps need to go through
        // SAF to write to transient volumes.)
        final List<DiskInfo> disks = getDisks();
        for (DiskInfo disk : disks) {
            final String diskId = ();
            if (()) {
                (TAG, "Found adoptable " + diskId + "; wiping");
                try {
                    // TODO: switch to explicit wipe command when we have it,
                    // for now rely on the fact that vfat format does a wipe
                    (diskId);
                } catch (Exception e) {
                    (TAG, "Failed to wipe " + diskId + ", but soldiering onward", e);
                }
            } else {
                (TAG, "Ignorning non-adoptable disk " + ());
            }
        }
    }

    /** {@hide} */
    @UnsupportedAppUsage
    public void partitionPublic(String diskId) {
        try {
            (diskId);
        } catch (RemoteException e) {
            throw ();
        }
    }