CM android的CMUpdater分析(二)

至於爲何要在這裏講解android系統源碼中的系統更新,我已經在上一篇《 CM android的CMUpdater分析(一)》中介紹了。在上一篇中,主要講解了在eclipse中如何搭建系統應用的開發環境,現在我們就使用eclipse來分析CMUpdater源碼。該系統更新是CM修改原生android的基礎上實現的。通過分析android系統的應用源碼,可以學到一些很好的思想和編程方法學。好了,廢話少說,現在就開始我們的學習之旅。

首先,在開始介紹之前,我先把之前根據CMUpdater源碼分析來的框圖放到上來,大家先看框圖,把系統更新的整體流程大體瞭解一下。

這裏寫圖片描述

通過這個框圖,看上去挺複雜,其實是挺簡單的,就是Service檢查更新,後臺下載更新,包括全安裝包或者是增量更新包,下載完成之後,安裝更新,重啓,安裝完成。

現在我們從代碼開始,進行分析。

首先,我們先來看一個app項目中,所有的activity和service,就是要查看AndroidManifest.xml文件。通過分析該代碼,我們看到,在CMUpdater中的入口Activity是UpdatesSettings,同時在
AndroidManifest.xml文件中,還靜態註冊了四個receiver,其中包括:

  • UpdateCheckReceiver : 在該receiver中註冊了兩個action,其中包括BOOT_COMPLETED和CONNECTIVITY_CHANGE,該receiver用於在系統啓動後或者是網絡連接發生變化的時候,進行檢查系統更新。
  • DownloadReceiver : 該receiver也註冊了兩個action,包括DOWNLOAD_COMPLETE和START_DOWNLOAD,當下載完成和開始下載廣播發出之後,進行相應的操作。
  • NotificationClickReceiver,該廣播接收器註冊了一個DOWNLOAD_NOTIFICATION_CLICKED廣播,當接收到下載提醒框被點擊的時候,進行更新操作。
  • CheckFinishReceiver : 該廣播接收器用於接收UPDATE_CHECK_FINISHED廣播,當檢查更新完成之後,刷新列表。

同時,在該xml文件中,也註冊了幾個Service:

  • CMDashClockExtension : 該服務用於檢查時間,用戶可以選擇某個時間點,進行檢查更新。
  • UpdateCheckService : 該服務的操作就是用於檢查更新,檢查更新完成之後,發出檢查更新完成的廣播。
  • DownloadService : 顧名思義,下載服務,也就是說該服務是用來下載系統更新的。
  • DownloadCompleteIntentService : 下載完成服務,當下載完成之後,發出下載完成廣播。

好了,現在我們先進入入口Activity來看一下。

進入到UpdateSettings.java文件,可以看到,該類中註冊了一個Receiver,該接收器的實現爲:


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            //如果Action爲ACTION_DOWNLOAD_STARTED,即爲下載開始
            if (DownloadReceiver.ACTION_DOWNLOAD_STARTED.equals(action)) {
                mDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                mUpdateHandler.post(mUpdateProgress);  //更新ProgressBar
                //如果Action爲ACTION_CHECK_FINISHED,即爲檢查更新完成
            } else if (UpdateCheckService.ACTION_CHECK_FINISHED.equals(action)) {
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;

                    //獲取系統更新的條數
                    int count = intent.getIntExtra(UpdateCheckService.EXTRA_NEW_UPDATE_COUNT, -1);
                    if (count == 0) {  // 如果爲0,提醒用戶未找到
                        Toast.makeText(UpdatesSettings.this, R.string.no_updates_found,
                                Toast.LENGTH_SHORT).show();
                    } else if (count < 0) {  //如果小於0,則表示檢查更新失敗
                        Toast.makeText(UpdatesSettings.this, R.string.update_check_failed,
                                Toast.LENGTH_LONG).show();
                    }
                }
                //如果其他都不是,表示更新完成,並且有更新,則刷新UI
                updateLayout();
            }
        }
    };

當用戶點擊item(MENU_REFRESH)之後,手動進行更新檢查,即爲checkForUpdates()


    private void checkForUpdates() {
        if (mProgressDialog != null) {
            return;
        }

        // 未連接網絡,提示用戶並返回
        if (!Utils.isOnline(this)) {
            Toast.makeText(this, R.string.data_connection_required, Toast.LENGTH_SHORT).show();
            return;
        }

        //彈出進度條,用戶提示用戶正在檢查更新
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle(R.string.checking_for_updates);
        mProgressDialog.setMessage(getString(R.string.checking_for_updates));
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                //當用戶點擊取消後,提醒服務程序,取消檢查更新操作
                Intent cancelIntent = new Intent(UpdatesSettings.this, UpdateCheckService.class);
                cancelIntent.setAction(UpdateCheckService.ACTION_CANCEL_CHECK);
                startService(cancelIntent);
                mProgressDialog = null;
            }
        });

        //開啓服務程序進行檢查更新
        Intent checkIntent = new Intent(UpdatesSettings.this, UpdateCheckService.class);
        checkIntent.setAction(UpdateCheckService.ACTION_CHECK);
        startService(checkIntent);

        mProgressDialog.show();
    }

現在我們進入檢查更新服務程序,即UpdateCheckService。在服務程序的啓動方法onStartCommand()檢查用戶的操作是取消檢查還是檢查更新,如果是取消檢查,就將位於請求列表中的請求刪除掉。


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //取消檢查更新
        if (TextUtils.equals(intent.getAction(), ACTION_CANCEL_CHECK)) {
            ((UpdateApplication) getApplicationContext()).getQueue().cancelAll(TAG);
            return START_NOT_STICKY;
        }

        return super.onStartCommand(intent, flags, startId);
    }

接着,服務程序調用getAvailableUpdates()來檢查可用更新,我們來看一下這個方法:

   private void getAvailableUpdates() {
        // Get the type of update we should check for
        int updateType = Utils.getUpdateType();

        // Get the actual ROM Update Server URL
        URI updateServerUri = getServerURI();

Log.e(TAG, updateServerUri.toString());

        UpdatesJsonObjectRequest request;

        try {
            request = new UpdatesJsonObjectRequest(updateServerUri.toASCIIString(),
                    Utils.getUserAgentString(this), buildUpdateRequest(updateType), this, this);
            // Set the tag for the request, reuse logging tag
            request.setTag(TAG);
        } catch (JSONException e) {
            Log.e(TAG, "Could not build request", e);
            return;
        }

        ((UpdateApplication) getApplicationContext()).getQueue().add(request);
    }

這個代碼很好理解,就是封裝一下請求信息,封裝爲請求對象,將該請求對象添加到請求隊列中,等待從服務器中獲取信息。請求對象的封裝是通過buildUpdateRequest()方法來實現的。

接着,服務程序通過回調函數onResponse()來獲取相應的服務器反饋信息。


    @Override
    public void onResponse(JSONObject jsonObject) {
        int updateType = Utils.getUpdateType();

        LinkedList<UpdateInfo> lastUpdates = State.loadState(this);
        LinkedList<UpdateInfo> updates = parseJSON(jsonObject.toString(), updateType);

        int newUpdates = 0, realUpdates = 0;
        for (UpdateInfo ui : updates) {
            if (!lastUpdates.contains(ui)) {
                newUpdates++;
            }
            if (ui.isNewerThanInstalled()) {
                realUpdates++;
            }
        }

        Intent intent = new Intent(ACTION_CHECK_FINISHED);
        intent.putExtra(EXTRA_UPDATE_COUNT, updates.size());
        intent.putExtra(EXTRA_REAL_UPDATE_COUNT, realUpdates);
        intent.putExtra(EXTRA_NEW_UPDATE_COUNT, newUpdates);

        recordAvailableUpdates(updates, intent);
        State.saveState(this, updates);
    }

在該回調函數中,將更新信息放到更新列表中,同時通過調用recordAvailableUpdates()發送actionACTION_CHECK_FINISHED的廣播給UpdateSettings中。接着UpdateSettings調用updateLayout()更新UI,同時調用refreshPreferences()接着調用回調函數onStartDownload()來通知DownloadReceiver進行下載。

我們先來看一下recordAvailableUpdates()函數的實現:


    private void recordAvailableUpdates(LinkedList<UpdateInfo> availableUpdates,
            Intent finishedIntent) {

        if (availableUpdates == null) {
            sendBroadcast(finishedIntent);
            return;
        }

        //保存上次更新時間,然後確保啓動檢查更新完成是正確的
        Date d = new Date();
        PreferenceManager.getDefaultSharedPreferences(UpdateCheckService.this).edit()
                .putLong(Constants.LAST_UPDATE_CHECK_PREF, d.getTime())
                .putBoolean(Constants.BOOT_CHECK_COMPLETED, true)
                .apply();

        int realUpdateCount = finishedIntent.getIntExtra(EXTRA_REAL_UPDATE_COUNT, 0);
        UpdateApplication app = (UpdateApplication) getApplicationContext();

        // Write to log
        Log.i(TAG, "The update check successfully completed at " + d + " and found "
                + availableUpdates.size() + " updates ("
                + realUpdateCount + " newer than installed)");

        //如果程序被關掉了,則在提醒框中顯示更新信息
        if (realUpdateCount != 0 && !app.isMainActivityActive()) {
            // There are updates available
            // The notification should launch the main app
            Intent i = new Intent(this, UpdatesSettings.class);
            i.putExtra(UpdatesSettings.EXTRA_UPDATE_LIST_UPDATED, true);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
                    PendingIntent.FLAG_ONE_SHOT);

            Resources res = getResources();
            String text = res.getQuantityString(R.plurals.not_new_updates_found_body,
                    realUpdateCount, realUpdateCount);

            // Get the notification ready
            Notification.Builder builder = new Notification.Builder(this)
                    .setSmallIcon(R.drawable.cm_updater)
                    .setWhen(System.currentTimeMillis())
                    .setTicker(res.getString(R.string.not_new_updates_found_ticker))
                    .setContentTitle(res.getString(R.string.not_new_updates_found_title))
                    .setContentText(text)
                    .setContentIntent(contentIntent)
                    .setAutoCancel(true);

            LinkedList<UpdateInfo> realUpdates = new LinkedList<UpdateInfo>();
            for (UpdateInfo ui : availableUpdates) {
                if (ui.isNewerThanInstalled()) {
                    realUpdates.add(ui);
                }
            }

            Collections.sort(realUpdates, new Comparator<UpdateInfo>() {
                @Override
                public int compare(UpdateInfo lhs, UpdateInfo rhs) {
                    /* sort by date descending */
                    long lhsDate = lhs.getDate();
                    long rhsDate = rhs.getDate();
                    if (lhsDate == rhsDate) {
                        return 0;
                    }
                    return lhsDate < rhsDate ? 1 : -1;
                }
            });

            Notification.InboxStyle inbox = new Notification.InboxStyle(builder)
                    .setBigContentTitle(text);
            int added = 0, count = realUpdates.size();

            for (UpdateInfo ui : realUpdates) {
                if (added < EXPANDED_NOTIF_UPDATE_COUNT) {
                    inbox.addLine(ui.getName());
                    added++;
                }
            }
            if (added != count) {
                inbox.setSummaryText(res.getQuantityString(R.plurals.not_additional_count,
                        count - added, count - added));
            }
            builder.setStyle(inbox);
            builder.setNumber(availableUpdates.size());

            //如果更新條數爲1 ,則直接發送開始下載更新的廣播
            if (count == 1) {
                i = new Intent(this, DownloadReceiver.class);
                i.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
                i.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) realUpdates.getFirst());
                PendingIntent downloadIntent = PendingIntent.getBroadcast(this, 0, i,
                        PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

                builder.addAction(R.drawable.ic_tab_download,
                        res.getString(R.string.not_action_download), downloadIntent);
            }

            // Trigger the notification
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.notify(R.string.not_new_updates_found_title, builder.build());
        }

        //發送廣播,提醒UpdateSettings類
        sendBroadcast(finishedIntent);
    }

updateLayout()函數中會更新UI,用戶可以點擊下載按鈕進行更新下載。

當下載開始之後,會廣播給`DownloadReceiver’接收器。


     @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (ACTION_START_DOWNLOAD.equals(action)) {
            UpdateInfo ui = (UpdateInfo) intent.getParcelableExtra(EXTRA_UPDATE_INFO);
            handleStartDownload(context, ui);
        } else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            handleDownloadComplete(context, id);
        } else if (ACTION_INSTALL_UPDATE.equals(action)) {
            StatusBarManager sb = (StatusBarManager) context.getSystemService(Context.STATUS_BAR_SERVICE);
            sb.collapsePanels();
            String fileName = intent.getStringExtra(EXTRA_FILENAME);
            try {
                Utils.triggerUpdate(context, fileName);
            } catch (IOException e) {
                Log.e(TAG, "Unable to reboot into recovery mode", e);
                Toast.makeText(context, R.string.apply_unable_to_reboot_toast,
                            Toast.LENGTH_SHORT).show();
                Utils.cancelNotification(context);
            }
        }
    }

在該接收器中,如果action爲ACTION_START_DOWNLOAD,則進行handleStartDownload()操作。


    private void handleStartDownload(Context context, UpdateInfo ui) {
        DownloadService.start(context, ui);
    }

啓動DownloadService開始操作。


    public static void start(Context context, UpdateInfo ui) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(EXTRA_UPDATE_INFO, (Parcelable) ui);
        context.startService(intent);
    }

靜態方法,啓動DownloadService服務。


    @Override
    protected void onHandleIntent(Intent intent) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        mInfo = intent.getParcelableExtra(EXTRA_UPDATE_INFO);

        if (mInfo == null) {
            Log.e(TAG, "Intent UpdateInfo extras were null");
            return;
        }

        try {
            getIncremental();
        } catch (IOException e) {
            downloadFullZip();
        }
    }

嘗試下載增量更新包,如果增量更新包報出異常,則下載全更新包。


    private void downloadFullZip() {
        Log.v(TAG, "Downloading full zip");

        // Build the name of the file to download, adding .partial at the end.  It will get
        // stripped off when the download completes
        String fullFilePath = "file://" + getUpdateDirectory().getAbsolutePath() +
                "/" + mInfo.getFileName() + ".partial";

        long downloadId = enqueueDownload(mInfo.getDownloadUrl(), fullFilePath);

        // Store in shared preferences
        mPrefs.edit()
                .putLong(Constants.DOWNLOAD_ID, downloadId)
                .putString(Constants.DOWNLOAD_MD5, mInfo.getMD5Sum())
                .apply();

        Utils.cancelNotification(this);

        Intent intent = new Intent(DownloadReceiver.ACTION_DOWNLOAD_STARTED);
        intent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, downloadId);
        sendBroadcast(intent);
    }

調用enqueueDownload()函數來獲取該下載在下載隊列中的id:


    private long enqueueDownload(String downloadUrl, String localFilePath) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
        String userAgent = Utils.getUserAgentString(this);
        if (userAgent != null) {
            request.addRequestHeader("User-Agent", userAgent);
        }
        request.setTitle(getString(R.string.app_name));
        request.setDestinationUri(Uri.parse(localFilePath));
        request.setAllowedOverRoaming(false);
        request.setVisibleInDownloadsUi(false);

        // TODO: this could/should be made configurable
        request.setAllowedOverMetered(true);

        final DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        return dm.enqueue(request);
    }

該操作相當於封裝請求服務器的信息,將該信息放到DownloadManager中,獲取id。

接着,向DownloadReceiver發送ACTION_DOWNLOAD_STARTED廣播。

當下載完成之後,會向DownloadReceiver發送廣播ACTION_DOWNLOAD_COMPLET,當接收器接到該廣播之後,則調用handleDownloadComplete(context, id)函數來處理下載完成的安裝包。


    private void handleDownloadComplete(Context context, long id) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        long enqueued = prefs.getLong(Constants.DOWNLOAD_ID, -1);
        if (enqueued < 0 || id < 0 || id != enqueued) {
            return;
        }

        String downloadedMD5 = prefs.getString(Constants.DOWNLOAD_MD5, "");
        String incrementalFor = prefs.getString(Constants.DOWNLOAD_INCREMENTAL_FOR, null);

        // Send off to DownloadCompleteIntentService
        Intent intent = new Intent(context, DownloadCompleteIntentService.class);
        intent.putExtra(Constants.DOWNLOAD_ID, id);
        intent.putExtra(Constants.DOWNLOAD_MD5, downloadedMD5);
        intent.putExtra(Constants.DOWNLOAD_INCREMENTAL_FOR, incrementalFor);
        context.startService(intent);

        // Clear the shared prefs
        prefs.edit()
                .remove(Constants.DOWNLOAD_MD5)
                .remove(Constants.DOWNLOAD_ID)
                .remove(Constants.DOWNLOAD_INCREMENTAL_FOR)
                .apply();
    }

通過md5檢查完整性,接着啓動DownloadCompleteIntentService服務來安裝更新。


    @Override
    protected void onHandleIntent(Intent intent) {
        if (!intent.hasExtra(Constants.DOWNLOAD_ID) ||
                !intent.hasExtra(Constants.DOWNLOAD_MD5)) {
            return;
        }

        long id = intent.getLongExtra(Constants.DOWNLOAD_ID, -1);
        String downloadedMD5 = intent.getStringExtra(Constants.DOWNLOAD_MD5);
        String incrementalFor = intent.getStringExtra(Constants.DOWNLOAD_INCREMENTAL_FOR);

        Intent updateIntent = new Intent(this, UpdatesSettings.class);
        updateIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

        int status = fetchDownloadStatus(id);
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            // Get the full path name of the downloaded file and the MD5

            // Strip off the .partial at the end to get the completed file
            String partialFileFullPath = fetchDownloadPartialPath(id);

            if (partialFileFullPath == null) {
                displayErrorResult(updateIntent, R.string.unable_to_download_file);
            }

            String completedFileFullPath = partialFileFullPath.replace(".partial", "");

            File partialFile = new File(partialFileFullPath);
            File updateFile = new File(completedFileFullPath);
            partialFile.renameTo(updateFile);

            // Start the MD5 check of the downloaded file
            if (MD5.checkMD5(downloadedMD5, updateFile)) {
                // We passed. Bring the main app to the foreground and trigger download completed
                updateIntent.putExtra(UpdatesSettings.EXTRA_FINISHED_DOWNLOAD_ID, id);
                updateIntent.putExtra(UpdatesSettings.EXTRA_FINISHED_DOWNLOAD_PATH,
                        completedFileFullPath);
                updateIntent.putExtra(UpdatesSettings.EXTRA_FINISHED_DOWNLOAD_INCREMENTAL_FOR,
                        incrementalFor);
                displaySuccessResult(updateIntent, updateFile);
            } else {
                // We failed. Clear the file and reset everything
                mDm.remove(id);

                if (updateFile.exists()) {
                    updateFile.delete();
                }
                displayErrorResult(updateIntent, R.string.md5_verification_failed);
            }
        } else if (status == DownloadManager.STATUS_FAILED) {
            // The download failed, reset
            mDm.remove(id);
            displayErrorResult(updateIntent, R.string.unable_to_download_file);
        }
    }

該服務通過封裝Intent來返回UpdateSettings中的onNewIntent()函數來進行處理。


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // Check if we need to refresh the screen to show new updates
        if (intent.getBooleanExtra(EXTRA_UPDATE_LIST_UPDATED, false)) {
            updateLayout();
        }

        //檢查下載完成
        checkForDownloadCompleted(intent);
    }

我們來看一下checkForDownloadCompleted()函數的實現:


    private void checkForDownloadCompleted(Intent intent) {
        if (intent == null) {
            return;
        }

        long downloadId = intent.getLongExtra(EXTRA_FINISHED_DOWNLOAD_ID, -1);
        if (downloadId < 0) {
            return;
        }

        String fullPathName = intent.getStringExtra(EXTRA_FINISHED_DOWNLOAD_PATH);
        if (fullPathName == null) {
            return;
        }

        String fileName = new File(fullPathName).getName();

        // If this is an incremental, find matching target and mark it as downloaded.
        String incrementalFor = intent.getStringExtra(EXTRA_FINISHED_DOWNLOAD_INCREMENTAL_FOR);
        if (incrementalFor != null) {
            UpdatePreference pref = (UpdatePreference) mUpdatesList.findPreference(incrementalFor);
            if (pref != null) {
                pref.setStyle(UpdatePreference.STYLE_DOWNLOADED);
                pref.getUpdateInfo().setFileName(fileName);
                //調用更新安裝
                onStartUpdate(pref);
            }
        } else {
            // Find the matching preference so we can retrieve the UpdateInfo
            UpdatePreference pref = (UpdatePreference) mUpdatesList.findPreference(fileName);
            if (pref != null) {
                pref.setStyle(UpdatePreference.STYLE_DOWNLOADED);
                onStartUpdate(pref);
            }
        }

        resetDownloadState();
    }

該函數通過調用onStartUpdate(pref)來安裝更新:


    @Override
    public void onStartUpdate(UpdatePreference pref) {
        final UpdateInfo updateInfo = pref.getUpdateInfo();

        // Prevent the dialog from being triggered more than once
        if (mStartUpdateVisible) {
            return;
        }

        mStartUpdateVisible = true;

        // Get the message body right
        String dialogBody = getString(R.string.apply_update_dialog_text, updateInfo.getName());

        // Display the dialog
        new AlertDialog.Builder(this)
                .setTitle(R.string.apply_update_dialog_title)
                .setMessage(dialogBody)
                .setPositiveButton(R.string.dialog_update, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            //提醒用戶是否安裝,用戶點擊確定之後,triggerUpdate()
                            Utils.triggerUpdate(UpdatesSettings.this, updateInfo.getFileName());
                        } catch (IOException e) {
                            Log.e(TAG, "Unable to reboot into recovery mode", e);
                            Toast.makeText(UpdatesSettings.this, R.string.apply_unable_to_reboot_toast,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mStartUpdateVisible = false;
                    }
                })
                .show();
    }

提醒用戶是否安裝,用戶點擊安裝之後,激發triggerUpdate()函數進行安裝:


    public static void triggerUpdate(Context context, String updateFileName) throws IOException {
        /*
         * Should perform the following steps.
         * 1.- mkdir -p /cache/recovery
         * 2.- echo 'boot-recovery' > /cache/recovery/command
         * 3.- if(mBackup) echo '--nandroid'  >> /cache/recovery/command
         * 4.- echo '--update_package=SDCARD:update.zip' >> /cache/recovery/command
         * 5.- reboot recovery
         */

        // Set the 'boot recovery' command
        Process p = Runtime.getRuntime().exec("sh");
        OutputStream os = p.getOutputStream();
        os.write("mkdir -p /cache/recovery/\n".getBytes());
        os.write("echo 'boot-recovery' >/cache/recovery/command\n".getBytes());

        // See if backups are enabled and add the nandroid flag
        /* TODO: add this back once we have a way of doing backups that is not recovery specific
           if (mPrefs.getBoolean(Constants.BACKUP_PREF, true)) {
           os.write("echo '--nandroid'  >> /cache/recovery/command\n".getBytes());
           }
           */

        // Add the update folder/file name
        // Emulated external storage moved to user-specific paths in 4.2
        String userPath = Environment.isExternalStorageEmulated() ? ("/" + UserHandle.myUserId()) : "";

        String cmd = "echo '--update_package=" + getStorageMountpoint(context) + userPath
            + "/" + Constants.UPDATES_FOLDER + "/" + updateFileName
            + "' >> /cache/recovery/command\n";
        os.write(cmd.getBytes());
        os.flush();

        // Trigger the reboot
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        powerManager.reboot("recovery");
    }

/*
* Should perform the following steps.
* 1.- mkdir -p /cache/recovery
* 2.- echo ‘boot-recovery’ > /cache/recovery/command
* 3.- if(mBackup) echo ‘–nandroid’ >> /cache/recovery/command
* 4.- echo ‘–update_package=SDCARD:update.zip’ >> /cache/recovery/command
* 5.- reboot recovery
*/

在註釋中,說明了必須運行下面步驟:

  1. mkdir -p /cache/recovery //創建文件夾
  2. echo ‘boot-recovery’ > /cache/recovery/command
  3. if(mBackup) echo ‘–nandroid’ >> /cache/recovery/command
  4. echo ‘–update_package=SDCARD:update.zip’ >> /cache/recovery/command
  5. reboot recovery

這五個命令運行完成之後,便會重啓安裝系統更新了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章