Initial Contribution
diff --git a/Android.mk b/Android.mk
new file mode 100644
index 0000000..dc71d90
--- /dev/null
+++ b/Android.mk
@@ -0,0 +1,11 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := user
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := Updater
+LOCAL_CERTIFICATE := platform
+
+include $(BUILD_PACKAGE)
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
new file mode 100644
index 0000000..a8bd12c
--- /dev/null
+++ b/AndroidManifest.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+** Copyright 2007, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+-->
+
+<manifest package="com.android.updater"
+    xmlns:android="http://schemas.android.com/apk/res/android">
+
+    <application android:label="@string/app_name">
+        <activity android:name="PesterActivity"
+		  android:label="@string/pester_label"
+                  android:launchMode="singleInstance"
+                  android:excludeFromRecents="true"
+		  android:permission="android.permission.FOTA_UPDATE"
+                  android:theme="@style/PesterDialog">
+            <intent-filter>
+                <action android:name="android.server.checkin.FOTA_READY"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+    <uses-permission android:name="android.permission.FOTA_UPDATE" />
+    <uses-permission android:name="android.permission.ACCESS_CACHE_FILESYSTEM" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+</manifest>
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2005-2008, The Android Open Source Project
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/res/layout/pester.xml b/res/layout/pester.xml
new file mode 100644
index 0000000..58112d9
--- /dev/null
+++ b/res/layout/pester.xml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+**
+** Copyright 2007-8, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+	      android:layout_width="fill_parent"
+	      android:layout_height="fill_parent"
+	      android:orientation="vertical">
+
+  <TextView android:id="@+id/message"
+	    android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+	    android:text="@string/message"
+	    android:textStyle="bold"
+            android:paddingTop="5dip"
+            android:paddingBottom="13dip"
+            android:paddingLeft="20dip"
+            android:paddingRight="20dip" />
+
+  <FrameLayout android:layout_width="fill_parent"
+               android:layout_height="wrap_content"
+               android:background="#c6c3c6"
+               android:minHeight="54dip"
+               android:paddingTop="4dip"
+               android:paddingLeft="2dip"
+               android:paddingRight="2dip">
+
+    <LinearLayout android:layout_width="fill_parent"
+		  android:layout_height="wrap_content"
+		  android:orientation="horizontal">
+
+      <Button android:id="@+id/now"
+              android:layout_width="fill_parent"
+              android:layout_height="fill_parent"
+              android:layout_weight="1"
+	      android:minWidth="100dip"
+	      android:text="@string/now_button" />
+
+      <Button android:id="@+id/later"
+              android:layout_width="fill_parent"
+              android:layout_height="fill_parent"
+              android:layout_weight="1"
+	      android:minWidth="100dip"
+	      android:text="@string/later_button" />
+
+    </LinearLayout>
+
+  </FrameLayout>
+
+</LinearLayout>
diff --git a/res/values-de-rDE/strings.xml b/res/values-de-rDE/strings.xml
new file mode 100644
index 0000000..d376501
--- /dev/null
+++ b/res/values-de-rDE/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="app_name">Aktualisierung</string>
+  <string name="later_button">Später aktualisieren</string>
+  <string name="message">
+        Während das Telefon die Aktualisierung durchführt, können Sie keine Notrufe absetzen. Das Telefon wird während der Aktualisierung neu gestartet.
+    </string>
+  <string name="now_button">Jetzt aktualisieren</string>
+  <string name="pester_label">Ein System-Update steht zur Verfügung</string>
+</resources>
diff --git a/res/values-en-rGB/strings.xml b/res/values-en-rGB/strings.xml
new file mode 100644
index 0000000..c8a8ea8
--- /dev/null
+++ b/res/values-en-rGB/strings.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="later_button">Update later</string>
+  <string name="message">
+        While your phone is updating, you cannot make emergency calls. Your phone will restart during update.  
+    </string>
+  <string name="now_button">Update now</string>
+  <string name="pester_label">A system update is available</string>
+</resources>
diff --git a/res/values-es-rUS/strings.xml b/res/values-es-rUS/strings.xml
new file mode 100644
index 0000000..18e5ba9
--- /dev/null
+++ b/res/values-es-rUS/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="app_name">Actualizador</string>
+  <string name="later_button">Actualizar más tarde</string>
+  <string name="message">
+        Mientras su teléfono se está actualizando, no puede realizar llamadas de emergencia. Su teléfono se reiniciará durante la actualización.  
+    </string>
+  <string name="now_button">Actualizar ahora</string>
+  <string name="pester_label">Se dispone de una actualización del sistema</string>
+</resources>
diff --git a/res/values-fr-rFR/strings.xml b/res/values-fr-rFR/strings.xml
new file mode 100644
index 0000000..080a243
--- /dev/null
+++ b/res/values-fr-rFR/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="app_name">Mise à jour</string>
+  <string name="later_button">Mettre à jour plus tard</string>
+  <string name="message">
+        Quand votre téléphone se met à jour, vous ne pouvez pas faire d\'appel d\'urgence. Votre téléphone redémarrera pendant la mise à jour.  
+    </string>
+  <string name="now_button">Mettre à jour maintenant</string>
+  <string name="pester_label">Une mise à jour système est disponible</string>
+</resources>
diff --git a/res/values-it-rIT/strings.xml b/res/values-it-rIT/strings.xml
new file mode 100644
index 0000000..5cc3776
--- /dev/null
+++ b/res/values-it-rIT/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="app_name">Programma per l'aggiornamento</string>
+  <string name="later_button">Aggiorna in seguito</string>
+  <string name="message">
+        Durante l'aggiornamento del telefono non è possibile eseguire chiamate di emergenza. Il telefono verrà riavviato durante l'aggiornamento.  
+    </string>
+  <string name="now_button">Aggiorna ora</string>
+  <string name="pester_label">È disponibile un aggiornamento del sistema</string>
+</resources>
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml
new file mode 100644
index 0000000..84d5138
--- /dev/null
+++ b/res/values-zh-rTW/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="app_name">更新程式</string>
+  <string name="later_button">稍後更新</string>
+  <string name="message">
+        正在更新電話時無法撥打緊急電話。電話將會在更新期間重新啟動。  
+    </string>
+  <string name="now_button">立即更新</string>
+  <string name="pester_label">目前有可用的系統更新</string>
+</resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
new file mode 100644
index 0000000..70fd427
--- /dev/null
+++ b/res/values/strings.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+** Copyright 2007, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+-->
+
+<resources>
+    <string name="app_name">Updater</string>
+    <string name="pester_label">A system update is available</string>
+    <string name="message">
+        While your phone is updating, you cannot make emergency calls. Your phone will restart during update.  
+    </string>
+
+    <string name="now_button">Update now</string>
+
+    <string name="later_button">Update later</string>
+</resources>
diff --git a/res/values/styles.xml b/res/values/styles.xml
new file mode 100644
index 0000000..234b0ba
--- /dev/null
+++ b/res/values/styles.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+  
+          http://www.apache.org/licenses/LICENSE-2.0
+  
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources>
+  <!-- PesterDialog is identical to Theme.Dialog except that the text
+       in the title is reduced from 18sp to 17sp, so that all of "A
+       system update is available" fits. -->
+
+  <style name="PesterDialog" parent="@android:Theme.Dialog">
+    <item name="android:windowTitleStyle">@style/PesterWindowTitle</item>
+  </style>
+
+  <style name="PesterWindowTitle" parent="@android:style/DialogWindowTitle">
+    <item name="android:textAppearance">@style/TextAppearance.PesterWindowTitle</item>
+  </style>
+
+  <style name="TextAppearance.PesterWindowTitle"
+	 parent="@android:style/TextAppearance.DialogWindowTitle">
+    <item name="android:textSize">17sp</item>
+  </style>
+</resources>
+
diff --git a/src/com/android/updater/PesterActivity.java b/src/com/android/updater/PesterActivity.java
new file mode 100644
index 0000000..d668244
--- /dev/null
+++ b/src/com/android/updater/PesterActivity.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.updater;
+
+import android.app.Activity;
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.SystemClock;
+import android.provider.Checkin;
+import com.android.internal.telephony.Phone;
+import com.android.internal.telephony.TelephonyIntents;
+import android.util.Log;
+import android.view.View;
+import android.view.Window;
+import android.widget.TextView;
+
+import java.io.File;
+
+/**
+ * A simple Activity that prompts the user for whether they want to update.
+ */
+public class PesterActivity extends Activity {
+    /** Class identifier for logging. */
+    private static final String TAG = "PesterActivity";
+
+    /** Alarm manager for setting prompt timeouts. */
+    private AlarmManager mAlarmManager;
+
+    /** Intent used to reboot and install an OTA package. */
+    private PendingIntent mInstallIntent;
+
+    /** Currently active prompt, if displayed. */
+    private static PesterActivity mActivityStarted;
+
+    /** @return whether a call is in progress (or the phone is ringing) */
+    private boolean inPhoneCall() {
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(TelephonyIntents.ACTION_PHONE_STATE_CHANGED);
+        Intent intent = registerReceiver(null, filter);
+        if (intent == null) return false;
+
+        String state = intent.getStringExtra(Phone.STATE_KEY);
+        if (state == null) return false;
+
+        try {
+            Phone.State phoneState = Phone.State.valueOf(state);
+            if (phoneState != Phone.State.IDLE) return true;
+        } catch (IllegalArgumentException e) {
+            // returned state isn't a valid enum value.
+            Log.e(TAG, "parsing phone state:", e);
+        }
+        return false;
+    }
+
+    /**
+     * @param intent to get first prompt time and interval schedule from
+     * @param currentTime (in elapsedRealtime) to look for a prompt after
+     * @return elapsedRealtime of the next prompt, or 0 if there are no more
+     */
+    private static long getNextPromptTime(Intent intent, long currentTime) {
+        int[] minutes = new int[] { 30 };  // Default: every 30 minutes forever
+        boolean forever = true;
+
+        String intervals = intent.getStringExtra("promptMinutes");
+        if (intervals != null) {
+            if (intervals.endsWith(",...")) {
+                forever = true;
+                intervals = intervals.substring(0, intervals.length() - 4);
+            } else {
+                forever = false;
+            }
+
+            try {
+                String[] split = intervals.split(",");
+                int[] parsed = new int[split.length];
+                for (int i = 0; i < split.length; i++) {
+                    parsed[i] = Integer.parseInt(split[i]);
+                }
+                minutes = parsed;  // Only after they've all been converted.
+            } catch (NumberFormatException e) {
+                Log.e(TAG, "Invalid prompt intervals: " + intervals, e);
+                forever = false;
+                // Use the defaults in this case.
+            }
+        }
+
+        // Run through the prompts until we find the next one after now.
+        long promptTime = intent.getLongExtra("firstPrompt", currentTime);
+        for (int i = 0; promptTime <= currentTime && i < minutes.length; i++) {
+            promptTime += minutes[i] * 60 * 1000;
+        }
+
+        // If the prompts go forever, just keep repeating the last interval.
+        while (forever && promptTime <= currentTime) {
+            if (minutes.length == 0 || minutes[minutes.length - 1] <= 0) {
+                Log.e(TAG, "Invalid infinite interval: " + intervals);
+                break;
+            }
+            promptTime += minutes[minutes.length - 1] * 60 * 1000;
+        }
+
+        return (promptTime <= currentTime) ? 0 : promptTime;
+    }
+
+    /**
+     * @param intent to get prompt delay settings from
+     * @return milliseconds to wait, 0 to wait forever
+     */
+    private static long getPromptTimeout(Intent intent) {
+        long value = 0;  // Default: wait forever (no timeout)
+        String seconds = intent.getStringExtra("timeoutSeconds");
+        try {
+            if (seconds != null) value = Long.parseLong(seconds) * 1000;
+        } catch (NumberFormatException e) {
+            Log.e(TAG, "Invalid timeout delay: " + seconds, e);
+        }
+        return value;
+    }
+
+    /** Install the update immediately and dismiss the dialog. */
+    private void installUpdate() {
+        if (mInstallIntent != null) {
+            try {
+                mInstallIntent.send();
+            } catch (PendingIntent.CanceledException e) {
+                throw new RuntimeException(e);  // Should not happen!
+            }
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+
+        requestWindowFeature(Window.FEATURE_LEFT_ICON);
+        setContentView(R.layout.pester);
+        getWindow().setFeatureDrawableResource(
+            Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);
+
+        // Install now -> broadcast the intent to install!
+        findViewById(R.id.now).setOnClickListener(
+            new View.OnClickListener() {
+                public void onClick(View v) {
+                    Log.i(TAG, "OTA update accepted by user!");
+                    Checkin.logEvent(getContentResolver(),
+                            Checkin.Events.Tag.FOTA_PROMPT_ACCEPT, null);
+                    installUpdate();
+                }
+            });
+
+        // Install later -> just go away, the alarm will trigger again.
+        findViewById(R.id.later).setOnClickListener(
+            new View.OnClickListener() {
+                public void onClick(View v) {
+                    Log.i(TAG, "OTA update dismissed by user");
+                    finish();
+                }
+            });
+    }
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        mActivityStarted = this;
+
+        onNewIntent(getIntent());
+        if (isFinishing()) return;  // onNewIntent() can do this
+
+        if (inPhoneCall()) {
+            Log.i(TAG, "OTA update prompt postponed by phone call");
+            Checkin.logEvent(getContentResolver(),
+                    Checkin.Events.Tag.FOTA_PROMPT_SKIPPED, null);
+            finish();
+            return;
+        }
+
+        Checkin.logEvent(getContentResolver(),
+                Checkin.Events.Tag.FOTA_PROMPT, null);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+
+        // The server can override the default text in the resource.
+        CharSequence message = getIntent().getStringExtra("promptMessage");
+        if (message == null) message = getText(R.string.message);
+        ((TextView) findViewById(R.id.message)).setText(message);
+
+        if (mInstallIntent != null) {
+            long delay = getPromptTimeout(getIntent());
+            if (delay > 0) {
+                Log.i(TAG, "OTA prompt timeout in " + delay / 1000 + " sec");
+                mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+                        SystemClock.elapsedRealtime() + delay, mInstallIntent);
+            }
+        }
+    }
+
+    @Override
+    public void onPause() {
+        if (mInstallIntent != null) {
+            mAlarmManager.cancel(mInstallIntent);
+            if (isFinishing()) {
+                Log.i(TAG, "OTA update prompt dismissed");
+                Checkin.logEvent(getContentResolver(),
+                        Checkin.Events.Tag.FOTA_PROMPT_REJECT, null);
+            }
+        }
+
+        super.onPause();
+    }
+
+    @Override
+    public void onStop() {
+        if (mActivityStarted == this) mActivityStarted = null;
+        super.onStop();
+    }
+
+    @Override
+    public void onNewIntent(Intent intent) {
+        // This activity is launched with SINGLE_TOP_LAUNCH, so this happens
+        // if the file being downloaded changes, or if the next alarm
+        // goes off while the prompt is still displayed.  We also call
+        // this function directly from onStart() so all Intents come here.
+        // Regardless, this is only called with the activity paused.
+
+        super.onNewIntent(intent);
+        setIntent(intent);
+
+        // This Extra must always be set by the caller.
+        File update = new File(intent.getStringExtra("updateFile"));
+        if (!update.exists()) {
+            // The update has gone away, maybe replaced by something newer?
+            Log.i(TAG, "OTA update no longer exists: " + update);
+            finish();
+            return;
+        }
+
+        Log.i(TAG, "OTA update available: " + update);
+        Uri uri = Uri.fromFile(update);
+        Intent install = new Intent("android.server.checkin.FOTA_INSTALL", uri);
+        mInstallIntent = PendingIntent.getBroadcast(this, 0, install, 0);
+
+        long now = SystemClock.elapsedRealtime();
+        long nextPrompt = getNextPromptTime(intent, now);
+        if (nextPrompt == 0) {
+            Log.i(TAG, "Installing overdue OTA update without prompting");
+            installUpdate();
+            return;
+        }
+
+        // Use FLAG_CANCEL_CURRENT because the Intent differs only in extras.
+        Log.i(TAG, "Next OTA prompt in " + (nextPrompt - now) / 1000 + " sec");
+        mAlarmManager.set(
+                AlarmManager.ELAPSED_REALTIME_WAKEUP, nextPrompt,
+                PendingIntent.getActivity(this, 0, intent,
+                        PendingIntent.FLAG_CANCEL_CURRENT));
+    }
+}