Android6.0リセットで出荷時設定に復元するプロセスの分析

設定アプリケーションの[出荷時設定に戻す]ボタンをクリックした後のプロセス分析:

まず、grepコマンドを使用して「工場出荷時の設定に戻す」文字列を検索し、対応するレイアウトファイルを見つけます。

packages / apps / Settings / res / xml / privacy_settings.xml

    <PreferenceScreen
        android:key="factory_reset"
        android:title="@string/master_clear_title"
        settings:keywords="@string/keywords_factory_data_reset"
        android:fragment="com.android.settings.MasterClear" />
このノードの下に、次のような文が表示されます。

android:fragment="com.android.settings.MasterClear"
この文は、「工場出荷時の設定に戻す」という項目をクリックすると、MasterClear.javaのフラグメントサブクラスに直接ジャンプすることを意味します。
まず、レイアウトファイルをロードするonCreateView()メソッドを確認します。

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (!Process.myUserHandle().isOwner()
                || UserManager.get(getActivity()).hasUserRestriction(
                UserManager.DISALLOW_FACTORY_RESET)) {
            return inflater.inflate(R.layout.master_clear_disallowed_screen, null);
        }

        mContentView = inflater.inflate(R.layout.master_clear, null);

        establishInitialState();
        return mContentView;
    }
ユーザーが「工場出荷時設定に復元」する権限を持っているかどうかを判断し、判断結果に従ってレイアウトをロードします。分析は「工場出荷時設定に復元」プロセスであるため、すべて直接デフォルトでmaster_clear.xmlレイアウトをロードします。
次に、betainInitialState()メソッドを見てみましょう。このメソッドは主に、対応するクリックイベントを設定せずにレイアウトコントロールを初期化するために使用されます。

    /**
     * In its initial state, the activity presents a button for the user to
     * click in order to initiate a confirmation sequence.  This method is
     * called from various other points in the code to reset the activity to
     * this base state.
     *
     * <p>Reinflating views from resources is expensive and prevents us from
     * caching widget pointers, so we use a single-inflate pattern:  we lazy-
     * inflate each view, caching all of the widget pointers we'll need at the
     * time, then simply reuse the inflated views directly whenever we need
     * to change contents.
     */
    private void establishInitialState() {
        mInitiateButton = (Button) mContentView.findViewById(R.id.initiate_master_clear);
        mInitiateButton.setOnClickListener(mInitiateListener);
        mExternalStorageContainer = mContentView.findViewById(R.id.erase_external_container);
        mExternalStorage = (CheckBox) mContentView.findViewById(R.id.erase_external);

        /*
         * If the external storage is emulated, it will be erased with a factory
         * reset at any rate. There is no need to have a separate option until
         * we have a factory reset that only erases some directories and not
         * others. Likewise, if it's non-removable storage, it could potentially have been
         * encrypted, and will also need to be wiped.
         */
        boolean isExtStorageEmulated = false;
        StorageHelpUtil mStorageHelpUtil = new StorageHelpUtil();
        if (mStorageHelpUtil.getSdCardPath(getActivity()) != null) {
            isExtStorageEmulated = true;
        }
        if (isExtStorageEmulated) {
            mExternalStorageContainer.setVisibility(View.VISIBLE);

            final View externalOption = mContentView.findViewById(R.id.erase_external_option_text);
            externalOption.setVisibility(View.VISIBLE);

            final View externalAlsoErased = mContentView.findViewById(R.id.also_erases_external);
            externalAlsoErased.setVisibility(View.VISIBLE);

            // If it's not emulated, it is on a separate partition but it means we're doing
            // a force wipe due to encryption.
            mExternalStorage.setChecked(!isExtStorageEmulated);
        } else {
                mExternalStorageContainer.setVisibility(View.GONE);
                final View externalOption = mContentView.findViewById(R.id.erase_external_option_text);
                externalOption.setVisibility(View.GONE);
            mExternalStorageContainer.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mExternalStorage.toggle();
                }
            });
        }

        final UserManager um = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
        loadAccountList(um);
        StringBuffer contentDescription = new StringBuffer();
        View masterClearContainer = mContentView.findViewById(R.id.master_clear_container);
        getContentDescription(masterClearContainer, contentDescription);
        masterClearContainer.setContentDescription(contentDescription);
    }
1. [工場出荷時の設定に戻す]ボタンを初期化し、クリックイベントを設定してmInitiateListenerをリッスンしない;
2. SDカードが挿入されているかどうかを確認します。挿入されている場合は、SDカード をクリアするかどうかのリマインダーメッセージが表示され、インスタンス化します。チェックボックスのチェックボックスを
オンにして、クリックイベントを設定します 。3。ユーザーリストをロードします。loadAccountList();
4.リマインダー情報領域をインスタンス化し、インターフェイスにリマインダー情報を表示します。

次に、mInitiateListenerリスナーを見てください。

    /**
     * If the user clicks to begin the reset sequence, we next require a
     * keyguard confirmation if the user has currently enabled one.  If there
     * is no keyguard available, we simply go to the final confirmation prompt.
     */
    private final Button.OnClickListener mInitiateListener = new Button.OnClickListener() {

        public void onClick(View v) {
            if (!runKeyguardConfirmation(KEYGUARD_REQUEST)) {
                Intent intent = new Intent("android.settings.PASSWORD_MANAGER");
                startActivityForResult(intent,PASSWORD_MANAGER);
            }
        }
    };
startActivityForResult()メソッドはパスワードインターフェイスに入り、結果を返します。onActivityResult()メソッドを直接見てみましょう。

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode != KEYGUARD_REQUEST && requestCode != PASSWORD_MANAGER) {
            return;
        } else if (requestCode == PASSWORD_MANAGER) {
             if (resultCode == Activity.RESULT_OK) {
                 validatePassword = data.getExtras().getBoolean("password");
                 if (validatePassword) {
                    showFinalConfirmation();
                 }
             }
             return;
        }

        // If the user entered a valid keyguard trace, present the final
        // confirmation prompt; otherwise, go back to the initial state.
        if (resultCode == Activity.RESULT_OK) {
            showFinalConfirmation();
        } else {
            establishInitialState();
        }
    }
パスワードが確認されたら、showFinalConfirmation()メソッドを呼び出します。
    private void showFinalConfirmation() {
        Bundle args = new Bundle();
        args.putBoolean(ERASE_EXTERNAL_EXTRA, mExternalStorage.isChecked());
        ((SettingsActivity) getActivity()).startPreferencePanel(MasterClearConfirm.class.getName(),
                args, R.string.master_clear_confirm_title, null, null, 0);
    }
MasterClearConfirm.javaと入力し、クリアSDカードデータをチェックするかどうかのパラメーターを渡します
。MasterClearConfirm.javaクラスは「出荷時設定へのリセット」を開始するかどうかを確認するために使用されます。 このクラスでは、最も重要なdoMasterClearのみを考慮する必要があります。 ()メソッドCan

    private void doMasterClear() {
        Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.putExtra(Intent.EXTRA_REASON, "MasterClearConfirm");
        intent.putExtra(Intent.EXTRA_WIPE_EXTERNAL_STORAGE, mEraseSdCard);
        getActivity().sendBroadcast(intent);
        // Intent handling is asynchronous -- assume it will happen soon.
    }
このメソッドは主に、Androidシステムに「出荷時設定への復元」を開始するよう通知するブロードキャストを送信するために使用されます。最終的な受信メソッドブロードキャストは、
frameworks / base / services / core / java / com / android / server /MasterClearReceiver.javaクラスにあります。 ;

onReceiver()メソッド:

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_REMOTE_INTENT)) {
            if (!"google.com".equals(intent.getStringExtra("from"))) {
                Slog.w(TAG, "Ignoring master clear request -- not from trusted server.");
                return;
            }
        }

        final boolean shutdown = intent.getBooleanExtra("shutdown", false);
        final String reason = intent.getStringExtra(Intent.EXTRA_REASON);
        final boolean wipeExternalStorage = intent.getBooleanExtra(
                Intent.EXTRA_WIPE_EXTERNAL_STORAGE, false);

        Slog.w(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);
                    Log.wtf(TAG, "Still running after master clear?!");
                } catch (IOException e) {
                    Slog.e(TAG, "Can't perform master clear/factory reset", e);
                } catch (SecurityException e) {
                    Slog.e(TAG, "Can't perform master clear/factory reset", e);
                }
            }
        };
        if (wipeExternalStorage) {
            // thr will be started at the end of this task.
            new WipeAdoptableDisksTask(context, thr).execute();
        } else {
            thr.start();
        }
    }
ブロードキャストが送信される場所を比較することにより、2つのパラメーターreasonとwipeExternalStorageだけを気にする必要があります。

1.wipeExternalStorageがtrueの場合、sdcardデータをクリアする必要があることを意味します。非同期タスクが開始されます。

new WipeAdoptableDisksTask(context, thr).execute();
    private class WipeAdoptableDisksTask extends AsyncTask<Void, Void, Void> {
        private final Thread mChainedTask;
        private final Context mContext;
        private final ProgressDialog mProgressDialog;

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

        @Override
        protected void onPreExecute() {
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            mProgressDialog.setMessage(mContext.getText(R.string.progress_erasing));
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            Slog.w(TAG, "Wiping adoptable disks");
            StorageManager sm = (StorageManager) mContext.getSystemService(
                    Context.STORAGE_SERVICE);
            sm.wipeAdoptableDisks();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
            mChainedTask.start();
        }

    }
1)この時点でUIスレッドで
最初にonPreExecute()メソッドを実行します。ユーザーに通知するようにダイアログを設定します。2)doInBackground()メソッドを実行します。 このメソッドは通常、時間のかかる操作を実行するために使用されます。StorageManagerを使用します。 SDカードの内容をクリアする;
。私たちの非同期タスクが実行された後、3)最後に、onPostExecute()メソッドを実行し、このメソッドは、このメソッドに結果を返します。wipeExternalStorageが偽のときにも実行する必要がTHRのスレッドを開始し、後で分析されます。

2.wipeExternalStorageがfalseの場合、ユーザーデータのみをクリアする必要があることを意味します。現時点では、実行スレッドを開くだけで済みます。

thr.start();
        Thread thr = new Thread("Reboot") {
            @Override
            public void run() {
                try {
                    RecoverySystem.rebootWipeUserData(context, shutdown, reason);
                    Log.wtf(TAG, "Still running after master clear?!");
                } catch (IOException e) {
                    Slog.e(TAG, "Can't perform master clear/factory reset", e);
                } catch (SecurityException e) {
                    Slog.e(TAG, "Can't perform master clear/factory reset", e);
                }
            }
        };
RecoverySystem.javaのrebootWipeUserData()メソッドを呼び出します。

    /**
     * Reboots the device and wipes the user data and cache
     * partitions.  This is sometimes called a "factory reset", which
     * is something of a misnomer because the system partition is not
     * restored to its factory state.  Requires the
     * {@link android.Manifest.permission#REBOOT} permission.
     *
     * @param context   the Context to use
     * @param shutdown  if true, the device will be powered down after
     *                  the wipe completes, rather than being rebooted
     *                  back to the regular system.
     *
     * @throws IOException  if writing the recovery command file
     * fails, or if the reboot itself fails.
     * @throws SecurityException if the current user is not allowed to wipe data.
     *
     * @hide
     */
    public static void rebootWipeUserData(Context context, boolean shutdown, String reason)
            throws IOException {
        UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
        if (um.hasUserRestriction(UserManager.DISALLOW_FACTORY_RESET)) {
            throw new SecurityException("Wiping data is not allowed for this user.");
        }
        final ConditionVariable condition = new ConditionVariable();

        Intent intent = new Intent("android.intent.action.MASTER_CLEAR_NOTIFICATION");
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        context.sendOrderedBroadcastAsUser(intent, UserHandle.OWNER,
                android.Manifest.permission.MASTER_CLEAR,
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        condition.open();
                    }
                }, null, 0, null, null);

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

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

        String reasonArg = null;
        if (!TextUtils.isEmpty(reason)) {
            reasonArg = "--reason=" + sanitizeArg(reason);
        }

        final String localeArg = "--locale=" + Locale.getDefault().toString();
        bootCommand(context, shutdownArg, "--wipe_data", reasonArg, localeArg);
    }
1.現在のユーザーがデータをクリアする権限を持っているかどうかを確認します
。2。整然としたブロードキャストを送信し、整然としたブロードキャストが完了するまでスレッドを中断します
。3。コマンドパラメーターをカプセル化し、bootCommand()メソッドを実行します。

    /**
     * Reboot into the recovery system with the supplied argument.
     * @param args to pass to the recovery utility.
     * @throws IOException if something goes wrong.
     */
    private static void bootCommand(Context context, String... args) throws IOException {
        RECOVERY_DIR.mkdirs();  // In case we need it
        COMMAND_FILE.delete();  // In case it's not writable
        LOG_FILE.delete();

        FileWriter command = new FileWriter(COMMAND_FILE);
        try {
            for (String arg : args) {
                if (!TextUtils.isEmpty(arg)) {
                    command.write(arg);
                    command.write("\n");
                }
            }
        } finally {
            command.close();
        }

        // Having written the command file, go ahead and reboot
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot(PowerManager.REBOOT_RECOVERY);

        throw new IOException("Reboot failed (no permissions?)");
    }
1.受信コマンドパラメータを「/ cache / recovery / command」ファイル
に書き込みます。2。PowerManager.javaのreboot()メソッドを呼び出して操作を再開します。

    public void reboot(String reason) {
        try {
            mService.reboot(false, reason, true);
        } catch (RemoteException e) {
        }
    }
AidlはPowerManagerService.javaのreboot()メソッドに転送されます。

        /**
         * 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, String reason, boolean wait) {
            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
            if (PowerManager.REBOOT_RECOVERY.equals(reason)) {
                mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
            }

            final long ident = Binder.clearCallingIdentity();
            try {
                shutdownOrRebootInternal(false, confirm, reason, wait);
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
        }
最初にREBOOTおよびRECOVERY権限があるかどうかを確認してから、shutdownOrRebootInternal()メソッドを呼び出します。

    private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
            final String reason, boolean wait) {
        if (mHandler == null || !mSystemReady) {
            throw new IllegalStateException("Too early to call shutdown() or reboot()");
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    if (shutdown) {
                        ShutdownThread.shutdown(mContext, confirm);
                    } else {
                        ShutdownThread.reboot(mContext, reason, confirm);
                    }
                }
            }
        };

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

        // PowerManager.reboot() is documented not to return so just wait for the inevitable.
        if (wait) {
            synchronized (runnable) {
                while (true) {
                    try {
                        runnable.wait();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }
このメソッドで最も重要なことは、Runnableでのrun()メソッドの実装です。前に渡されたシャットダウンはfalseであるため、次の呼び出しを続けます。

ShutdownThread.reboot(mContext, reason, confirm);
    /**
     * Request a clean shutdown, waiting for subsystems to clean up their
     * state etc.  Must be called from a Looper thread in which its UI
     * is shown.
     *
     * @param context Context used to display the shutdown progress dialog.
     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
     * @param confirm true if user confirmation is needed before shutting down.
     */
    public static void reboot(final Context context, String reason, boolean confirm) {
        mReboot = true;
        mRebootSafeMode = false;
        mRebootUpdate = false;
        mRebootReason = reason;
        shutdownInner(context, confirm);
    }
引き続きshutdownInner()メソッドを呼び出します。この時点では、confirmはfalseです
。shutdownInner()メソッドは非常に長いため、主な関数は、ダイアログを表示するかどうかを決定するための入力パラメーターconfirmに従って、ポップアップボックスを作成することです。これには、ユーザーがシャットダウンまたは再起動を確認してから、スレッドを開始する必要があります。シャットダウンまたは再起動操作を実行します。フォローアッププロセス分析は、別の記事を参照することができます: Android6.0シャットダウンシャットダウン&再起動プロセス分析


デバイスが再起動すると、自動的にリカバリモードに入り、/ cache / recovery / commandを読み取り、内容は「--wipe_data」で、データとキャッシュパーティションのクリアを開始します。クリアが成功すると、システムが再起動します。その後、通常のブートプロセスに入り、再利用します。システムパーティションのコンテンツは、ブート後に初期化されます。このプロセスは、最初のソフトウェアプログラミングプロセスと一致しています。
この時点で、出荷時設定へのリセットは完了しています。


工場出荷時設定への復元の概要:
1。MasterClearConfirm.javaで確認して、工場出荷時設定への復元操作を開始し、「工場出荷時設定への復元」のブロードキャストを送信します
。2.MasterClearReceiver.javaのMasterClearConfirm.javaからブロードキャストを受信します。 sdcardオプションをクリアするかどうか。対応する操作を実行します。3。RecoverySystem.rebootWipeUserData
()メソッドを呼び出してユーザーデータをクリアし、デバイスを再起動します。このメソッドの実行中に、「android.intent.action.MASTER_CLEAR_NOTIFICATION」をブロードキャストして「 / cache / repository / command "ファイルが発行され(コンテンツには" --wipe_data "が含まれます)、デバイスを再起動します
。4。再起動後にデバイスがリカバリモードに入った後、/ cache / recovery / commandを読み取り、コンテンツは次のようになります。 "--wipe_data";
5.読み取りコマンドに従い、データの消去データ
クリア操作を続行します; 6.正常にクリアした後、システムは再起動し、通常のブートプロセスに入ります。

おすすめ

転載: blog.csdn.net/Otaku_627/article/details/53899346