Merge "Merge "Network Operator" into "Mobile network" main activity."
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 87798ac..195fc7a 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -77,6 +77,7 @@
     <protected-broadcast android:name= "com.android.phone.vvm.omtp.sms.REQUEST_SENT" />
     <protected-broadcast android:name= "com.android.phone.vvm.ACTION_VISUAL_VOICEMAIL_SERVICE_EVENT" />
     <protected-broadcast android:name= "com.android.internal.telephony.CARRIER_VVM_PACKAGE_INSTALLED" />
+    <protected-broadcast android:name= "com.android.cellbroadcastreceiver.GET_LATEST_CB_AREA_INFO" />
 
     <uses-permission android:name="android.permission.BROADCAST_STICKY" />
     <uses-permission android:name="android.permission.CALL_PHONE" />
diff --git a/res/layout/emergency_dialer.xml b/res/layout/emergency_dialer.xml
index 3b91b07..a18596f 100644
--- a/res/layout/emergency_dialer.xml
+++ b/res/layout/emergency_dialer.xml
@@ -19,8 +19,8 @@
         android:id="@+id/top"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
-        android:paddingLeft="50dp"
-        android:paddingRight="50dp">
+        android:paddingLeft="36dp"
+        android:paddingRight="36dp">
 
     <LinearLayout
             android:layout_width="match_parent"
@@ -127,6 +127,7 @@
         android:id="@+id/floating_action_button_container"
         android:layout_width="@dimen/floating_action_button_width"
         android:layout_height="@dimen/floating_action_button_height"
+        android:layout_marginBottom="@dimen/floating_action_button_margin_bottom"
         android:layout_gravity="center_horizontal|bottom" >
 
         <ImageButton
diff --git a/res/values-hu/strings.xml b/res/values-hu/strings.xml
index 557b759..ba85bc5 100644
--- a/res/values-hu/strings.xml
+++ b/res/values-hu/strings.xml
@@ -476,7 +476,7 @@
     <string name="emergency_enable_radio_dialog_title" msgid="4627849966634578257">"Segélyhívás"</string>
     <string name="emergency_enable_radio_dialog_message" msgid="207613549344420291">"Rádió bekapcsolása..."</string>
     <string name="emergency_enable_radio_dialog_retry" msgid="5960061579996526883">"Nincs szolgáltatás. Újrapróbálkozás folyamatban…"</string>
-    <string name="radio_off_during_emergency_call" msgid="2535800034010306830">"Vészhívás során nem engedélyezheti a Repülős üzemmódot."</string>
+    <string name="radio_off_during_emergency_call" msgid="2535800034010306830">"Segélyhívás során nem engedélyezheti a Repülős üzemmódot."</string>
     <string name="dial_emergency_error" msgid="1509085166367420355">"A hívás sikertelen. A(z) <xliff:g id="NON_EMERGENCY_NUMBER">%s</xliff:g> szám nem segélyhívószám."</string>
     <string name="dial_emergency_empty_error" msgid="9130194953830414638">"A hívás sikertelen. Tárcsázzon segélyhívószámot."</string>
     <string name="dialerKeyboardHintText" msgid="9192914825413747792">"A tárcsázáshoz használja a billentyűzetet"</string>
diff --git a/res/values-zh-rHK/strings.xml b/res/values-zh-rHK/strings.xml
index 10f8e23..a92dbdc 100644
--- a/res/values-zh-rHK/strings.xml
+++ b/res/values-zh-rHK/strings.xml
@@ -219,8 +219,8 @@
     <string name="data_enable_summary" msgid="2382798156640007971">"允許使用數據"</string>
     <string name="dialog_alert_title" msgid="6751344986194435476">"注意"</string>
     <string name="roaming" msgid="7894878421600247140">"漫遊"</string>
-    <string name="roaming_enable" msgid="7331106985174381987">"漫遊時連線到數據傳輸服務"</string>
-    <string name="roaming_disable" msgid="1843417228755568110">"漫遊時連線到數據傳輸服務"</string>
+    <string name="roaming_enable" msgid="7331106985174381987">"漫遊時連線到數據服務"</string>
+    <string name="roaming_disable" msgid="1843417228755568110">"漫遊時連線到數據服務"</string>
     <string name="roaming_reenable_message" msgid="8913735676127858115">"您已離開主網絡覆蓋範圍,且已關閉數據漫遊服務,因此數據連線已中斷。"</string>
     <string name="roaming_warning" msgid="1603164667540144353">"您可能需要支付龐大的費用。"</string>
     <string name="roaming_alert_title" msgid="3654815360303826008">"要允許數據漫遊服務嗎?"</string>
@@ -360,7 +360,7 @@
     <item msgid="6043847456049107742">"1"</item>
   </string-array>
     <string name="cdma_activate_device" msgid="3793805892364814518">"啟動裝置"</string>
-    <string name="cdma_lte_data_service" msgid="4255018217292548962">"設定數據傳輸服務"</string>
+    <string name="cdma_lte_data_service" msgid="4255018217292548962">"設定數據服務"</string>
     <string name="carrier_settings_title" msgid="9028166176523012300">"流動網絡供應商設定"</string>
     <string name="fdn" msgid="7878832555095183202">"固定撥號號碼"</string>
     <string name="fdn_with_label" msgid="187084204115493366">"固定撥號 (<xliff:g id="SUBSCRIPTIONLABEL">%s</xliff:g>)"</string>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index a3c62a9..0a21d27 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -68,7 +68,7 @@
     <!-- Dimensions for Emergency Dialer and dialpad inside the in-call screen -->
     <dimen name="dialpad_horizontal_margin">4dp</dimen>
     <dimen name="dialpad_vertical_margin">2dp</dimen>
-    <dimen name="dialpad_digits_text_size">35sp</dimen>
+    <dimen name="dialpad_digits_text_size">40sp</dimen>
     <dimen name="dialpad_space_above_keys">29dp</dimen>
     <dimen name="dialpad_bottom_key_height">113dp</dimen>
 
@@ -106,5 +106,5 @@
          inside the Emergency Dialer than the regular Dialer. -->
     <dimen name="floating_action_button_width">67dp</dimen>
     <dimen name="floating_action_button_height">67dp</dimen>
-    <dimen name="floating_action_button_margin_bottom">26dp</dimen>
+    <dimen name="floating_action_button_margin_bottom">32dp</dimen>
 </resources>
diff --git a/src/com/android/phone/MobileNetworkSettings.java b/src/com/android/phone/MobileNetworkSettings.java
index f9465f4..b5f49eb 100644
--- a/src/com/android/phone/MobileNetworkSettings.java
+++ b/src/com/android/phone/MobileNetworkSettings.java
@@ -163,6 +163,7 @@
                 "com.android.settings.Settings$WirelessSettingsActivity";
 
         private SubscriptionManager mSubscriptionManager;
+        private TelephonyManager mTelephonyManager;
 
         //UI objects
         private ListPreference mButtonPreferredNetworkMode;
@@ -315,9 +316,7 @@
                         getActivity().getContentResolver(),
                         android.provider.Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL);
                 if (!TextUtils.isEmpty(tmpl)) {
-                    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(
-                            Context.TELEPHONY_SERVICE);
-                    String imsi = tm.getSubscriberId();
+                    String imsi = mTelephonyManager.getSubscriberId();
                     if (imsi == null) {
                         imsi = "";
                     }
@@ -366,7 +365,8 @@
         };
 
         private void initializeSubscriptions() {
-            if (getActivity().isDestroyed()) {
+            final Activity activity = getActivity();
+            if (activity == null || activity.isDestroyed()) {
                 // Process preferences in activity only if its not destroyed
                 return;
             }
@@ -522,15 +522,24 @@
         public void onCreate(Bundle icicle) {
             Log.i(LOG_TAG, "onCreate:+");
             super.onCreate(icicle);
+
+            final Activity activity = getActivity();
+            if (activity == null || activity.isDestroyed()) {
+                Log.e(LOG_TAG, "onCreate:- with no valid activity.");
+                return;
+            }
+
             mHandler = new MyHandler();
-            mUm = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
-            mSubscriptionManager = SubscriptionManager.from(getActivity());
+            mUm = (UserManager) activity.getSystemService(Context.USER_SERVICE);
+            mSubscriptionManager = SubscriptionManager.from(activity);
+            mTelephonyManager = (TelephonyManager) activity.getSystemService(
+                            Context.TELEPHONY_SERVICE);
 
             bindNetworkQueryService();
 
             if (mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
                 mUnavailable = true;
-                getActivity().setContentView(R.layout.telephony_disallowed_preference_screen);
+                activity.setContentView(R.layout.telephony_disallowed_preference_screen);
                 return;
             }
 
@@ -544,7 +553,7 @@
             mVideoCallingPref = (SwitchPreference) findPreference(BUTTON_VIDEO_CALLING_KEY);
 
             try {
-                Context con = getActivity().createPackageContext("com.android.systemui", 0);
+                Context con = activity.createPackageContext("com.android.systemui", 0);
                 int id = con.getResources().getIdentifier("config_show4GForLTE",
                         "bool", "com.android.systemui");
                 mShow4GForLTE = con.getResources().getBoolean(id);
@@ -575,7 +584,7 @@
 
             IntentFilter intentFilter = new IntentFilter(
                     TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
-            getActivity().registerReceiver(mPhoneChangeReceiver, intentFilter);
+            activity.registerReceiver(mPhoneChangeReceiver, intentFilter);
 
             initializeSubscriptions();
             Log.i(LOG_TAG, "onCreate:-");
@@ -596,7 +605,9 @@
         public void onDestroy() {
             unbindNetworkQueryService();
             super.onDestroy();
-            getActivity().unregisterReceiver(mPhoneChangeReceiver);
+            if (getActivity() != null && !getActivity().isDestroyed()) {
+                getActivity().unregisterReceiver(mPhoneChangeReceiver);
+            }
         }
 
         @Override
@@ -609,6 +620,11 @@
                 return;
             }
 
+            final Activity activity = getActivity();
+            if (activity == null || activity.isDestroyed()) {
+                Log.e(LOG_TAG, "onResume:- with no valid activity.");
+                return;
+            }
             // upon resumption from the sub-activity, make sure we re-enable the
             // preferences.
             getPreferenceScreen().setEnabled(true);
@@ -623,17 +639,14 @@
                 updatePreferredNetworkUIFromDb();
             }
 
-            if (ImsManager.isVolteEnabledByPlatform(getActivity())
-                    && ImsManager.isVolteProvisionedOnDevice(getActivity())) {
-                TelephonyManager tm =
-                        (TelephonyManager) getActivity().getSystemService(
-                                Context.TELEPHONY_SERVICE);
-                tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
+            if (ImsManager.isVolteEnabledByPlatform(activity)
+                    && ImsManager.isVolteProvisionedOnDevice(activity)) {
+                mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
             }
 
             // NOTE: Buttons will be enabled/disabled in mPhoneStateListener
-            boolean enh4glteMode = ImsManager.isEnhanced4gLteModeSettingEnabledByUser(getActivity())
-                    && ImsManager.isNonTtyOrTtyOnVolteEnabled(getActivity());
+            boolean enh4glteMode = ImsManager.isEnhanced4gLteModeSettingEnabledByUser(activity)
+                    && ImsManager.isNonTtyOrTtyOnVolteEnabled(activity);
             mButton4glte.setChecked(enh4glteMode);
 
             // Video calling and WiFi calling state might have changed.
@@ -669,7 +682,12 @@
         }
 
         private void updateBody() {
-            Context context = getActivity().getApplicationContext();
+            final Activity activity = getActivity();
+            if (activity == null || activity.isDestroyed()) {
+                Log.e(LOG_TAG, "updateBody with no valid activity.");
+                return;
+            }
+            Context context = activity.getApplicationContext();
             PreferenceScreen prefSet = getPreferenceScreen();
             boolean isLteOnCdma = mPhone.getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
             final int phoneSubId = mPhone.getSubId();
@@ -686,16 +704,14 @@
                 prefSet.addPreference(mButton4glte);
                 if (showEuiccSettings()) {
                     prefSet.addPreference(mEuiccSettingsPref);
-                    TelephonyManager tm =
-                        (TelephonyManager) getActivity()
-                                .getSystemService(Context.TELEPHONY_SERVICE);
-                    if (TextUtils.isEmpty(tm.getLine1Number())) {
+                    if (TextUtils.isEmpty(mTelephonyManager.getLine1Number())) {
                         mEuiccSettingsPref.setSummary(null);
                     } else {
                         mEuiccSettingsPref.setSummary(
                                 getEuiccSettingsSummary(
-                                        tm.getSimOperatorName(),
-                                        PhoneNumberUtils.formatNumber(tm.getLine1Number())));
+                                        mTelephonyManager.getSimOperatorName(),
+                                        PhoneNumberUtils.formatNumber(
+                                                mTelephonyManager.getLine1Number())));
                     }
                 }
             }
@@ -848,7 +864,7 @@
             }
 
             final boolean missingDataServiceUrl = TextUtils.isEmpty(
-                    android.provider.Settings.Global.getString(getActivity().getContentResolver(),
+                    android.provider.Settings.Global.getString(activity.getContentResolver(),
                             android.provider.Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL));
             if (!isLteOnCdma || missingDataServiceUrl) {
                 prefSet.removePreference(mLteDataServicePref);
@@ -856,8 +872,8 @@
                 android.util.Log.d(LOG_TAG, "keep ltePref");
             }
 
-            if (!(ImsManager.isVolteEnabledByPlatform(getActivity())
-                    && ImsManager.isVolteProvisionedOnDevice(getActivity()))
+            if (!(ImsManager.isVolteEnabledByPlatform(activity)
+                    && ImsManager.isVolteProvisionedOnDevice(activity))
                     || carrierConfig.getBoolean(
                         CarrierConfigManager.KEY_HIDE_ENHANCED_4G_LTE_BOOL)) {
                 Preference pref = prefSet.findPreference(BUTTON_4G_LTE_KEY);
@@ -868,14 +884,14 @@
 
             updateCallingCategory();
 
-            ActionBar actionBar = getActivity().getActionBar();
+            ActionBar actionBar = activity.getActionBar();
             if (actionBar != null) {
                 // android.R.id.home will be triggered in onOptionsItemSelected()
                 actionBar.setDisplayHomeAsUpEnabled(true);
             }
 
             // Enable link to CMAS app settings depending on the value in config.xml.
-            final boolean isCellBroadcastAppLinkEnabled = getActivity().getResources().getBoolean(
+            final boolean isCellBroadcastAppLinkEnabled = activity.getResources().getBoolean(
                     com.android.internal.R.bool.config_cellBroadcastAppLinks);
             if (!mUm.isAdminUser() || !isCellBroadcastAppLinkEnabled
                     || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS)) {
@@ -906,11 +922,11 @@
              * change dynamically such as when hot swapping sims.
              */
             boolean hasActiveSubscriptions = hasActiveSubscriptions();
-            TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(
-                    Context.TELEPHONY_SERVICE);
-            boolean canChange4glte = (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) &&
-                    ImsManager.isNonTtyOrTtyOnVolteEnabled(getActivity().getApplicationContext()) &&
-                    carrierConfig.getBoolean(
+            boolean canChange4glte =
+                    (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)
+                            && ImsManager.isNonTtyOrTtyOnVolteEnabled(
+                                    activity.getApplicationContext())
+                            && carrierConfig.getBoolean(
                             CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL);
             boolean useVariant4glteTitle = carrierConfig.getBoolean(
                     CarrierConfigManager.KEY_ENHANCED_4G_LTE_TITLE_VARIANT_BOOL);
@@ -966,13 +982,7 @@
             super.onPause();
             if (DBG) log("onPause:+");
 
-            if (ImsManager.isVolteEnabledByPlatform(getActivity())
-                    && ImsManager.isVolteProvisionedOnDevice(getActivity())) {
-                TelephonyManager tm =
-                        (TelephonyManager) getActivity().getSystemService(
-                                Context.TELEPHONY_SERVICE);
-                tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
-            }
+            mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
 
             mSubscriptionManager
                     .removeOnSubscriptionsChangedListener(mOnSubscriptionsChangeListener);
@@ -1595,8 +1605,6 @@
 
         private boolean isWorldMode() {
             boolean worldModeOn = false;
-            final TelephonyManager tm =
-                    (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
             final String configString = getResources().getString(R.string.config_world_mode);
 
             if (!TextUtils.isEmpty(configString)) {
@@ -1606,8 +1614,9 @@
                 if (configArray != null &&
                         ((configArray.length == 1 && configArray[0].equalsIgnoreCase("true"))
                                 || (configArray.length == 2 && !TextUtils.isEmpty(configArray[1])
-                                && tm != null
-                                && configArray[1].equalsIgnoreCase(tm.getGroupIdLevel1())))) {
+                                && mTelephonyManager != null
+                                && configArray[1].equalsIgnoreCase(
+                                        mTelephonyManager.getGroupIdLevel1())))) {
                     worldModeOn = true;
                 }
             }
diff --git a/src/com/android/services/telephony/PstnIncomingCallNotifier.java b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
index 72b659e..381c131 100644
--- a/src/com/android/services/telephony/PstnIncomingCallNotifier.java
+++ b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
@@ -139,7 +139,7 @@
             Connection connection = call.getLatestConnection();
             if (connection != null) {
                 String number = connection.getAddress();
-                if (number != null && Objects.equals(number, ccwi.number)) {
+                if (!TextUtils.isEmpty(number) && Objects.equals(number, ccwi.number)) {
                     sendIncomingCallIntent(connection);
                 }
             }
diff --git a/testapps/EmbmsServiceTestApp/AndroidManifest.xml b/testapps/EmbmsServiceTestApp/AndroidManifest.xml
index 526d3af..edcb5cb 100644
--- a/testapps/EmbmsServiceTestApp/AndroidManifest.xml
+++ b/testapps/EmbmsServiceTestApp/AndroidManifest.xml
@@ -33,6 +33,10 @@
         <action android:name="android.telephony.action.EmbmsDownload" />
       </intent-filter>
     </service>
+
+    <receiver android:name="com.android.phone.testapps.embmsmw.SideChannelReceiver"
+              android:enabled="true"
+              android:exported="true"/>
   </application>
 </manifest>
 
diff --git a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java
index f7abeb9..67083d7 100644
--- a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java
+++ b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java
@@ -47,6 +47,7 @@
 import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -152,29 +153,98 @@
         }
     };
 
+    private static EmbmsSampleDownloadService sInstance = null;
+
     private final Map<FrontendAppIdentifier, IMbmsDownloadManagerCallback> mAppCallbacks =
             new HashMap<>();
     private final Map<FrontendAppIdentifier, ComponentName> mAppReceivers = new HashMap<>();
     private final Map<FrontendAppIdentifier, String> mAppTempFileRoots = new HashMap<>();
     private final Map<FrontendAppIdentifier, Boolean> mDoesAppHaveActiveDownload =
             new ConcurrentHashMap<>();
+    // A map of app-identifiers to (maps of service-ids to sets of temp file uris in use)
+    private final Map<FrontendAppIdentifier, Map<String, Set<Uri>>> mTempFilesInUse =
+            new ConcurrentHashMap<>();
 
     private HandlerThread mHandlerThread;
     private Handler mHandler;
+    private int mDownloadDelayFactor = 1;
 
     @Override
     public IBinder onBind(Intent intent) {
         mHandlerThread = new HandlerThread("EmbmsTestDownloadServiceWorker");
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
+        sInstance = this;
         return mBinder.asBinder();
     }
 
+    public static EmbmsSampleDownloadService getInstance() {
+        return sInstance;
+    }
+
+    public void requestCleanup() {
+        // Assume that there's only one app, and do it for all the services.
+        FrontendAppIdentifier registeredAppId = mAppReceivers.keySet().iterator().next();
+        ComponentName appReceiver = mAppReceivers.values().iterator().next();
+        for (FileServiceInfo fileServiceInfo :
+                FileServiceRepository.getInstance(this).getAllFileServices()) {
+            Intent cleanupIntent = new Intent(MbmsDownloadManager.ACTION_CLEANUP);
+            cleanupIntent.setComponent(appReceiver);
+            cleanupIntent.putExtra(MbmsDownloadManager.EXTRA_SERVICE_INFO, fileServiceInfo);
+            cleanupIntent.putExtra(MbmsDownloadManager.EXTRA_TEMP_FILE_ROOT,
+                    mAppTempFileRoots.get(registeredAppId));
+            Set<Uri> tempFilesInUse =
+                    mTempFilesInUse.getOrDefault(registeredAppId, Collections.emptyMap())
+                            .getOrDefault(fileServiceInfo.getServiceId(), Collections.emptySet());
+            cleanupIntent.putExtra(MbmsDownloadManager.EXTRA_TEMP_FILES_IN_USE,
+                    new ArrayList<>(tempFilesInUse));
+            sendBroadcast(cleanupIntent);
+        }
+    }
+
+    public void requestExtraTempFiles(FileServiceInfo serviceInfo) {
+        // Assume one app, and do it for the specified service.
+        FrontendAppIdentifier registeredAppId = mAppReceivers.keySet().iterator().next();
+        ComponentName appReceiver = mAppReceivers.values().iterator().next();
+        Intent fdRequestIntent = new Intent(MbmsDownloadManager.ACTION_FILE_DESCRIPTOR_REQUEST);
+        fdRequestIntent.putExtra(MbmsDownloadManager.EXTRA_SERVICE_INFO, serviceInfo);
+        fdRequestIntent.putExtra(MbmsDownloadManager.EXTRA_FD_COUNT, 10);
+        fdRequestIntent.putExtra(MbmsDownloadManager.EXTRA_TEMP_FILE_ROOT,
+                mAppTempFileRoots.get(registeredAppId));
+        fdRequestIntent.setComponent(appReceiver);
+
+        sendOrderedBroadcast(fdRequestIntent,
+                null, // receiverPermission
+                new BroadcastReceiver() {
+                    @Override
+                    public void onReceive(Context context, Intent intent) {
+                        int result = getResultCode();
+                        Bundle extras = getResultExtras(false);
+                        Log.i(LOG_TAG, "Received extra temp files. Result " + result);
+                        if (extras != null) {
+                            Log.i(LOG_TAG, "Got "
+                                    + extras.getParcelableArrayList(
+                                    MbmsDownloadManager.EXTRA_FREE_URI_LIST).size()
+                                    + " fds");
+                        }
+                    }
+                },
+                null, // scheduler
+                Activity.RESULT_OK,
+                null, // initialData
+                null /* initialExtras */);
+    }
+
+    public void delayDownloads(int factor) {
+        mDownloadDelayFactor = factor;
+    }
+
     private void sendFdRequest(DownloadRequest request, FrontendAppIdentifier appKey) {
         int numFds = getNumFdsNeededForRequest(request);
         // Compose the FILE_DESCRIPTOR_REQUEST_INTENT
         Intent requestIntent = new Intent(MbmsDownloadManager.ACTION_FILE_DESCRIPTOR_REQUEST);
-        requestIntent.putExtra(MbmsDownloadManager.EXTRA_REQUEST, request);
+        requestIntent.putExtra(MbmsDownloadManager.EXTRA_SERVICE_INFO,
+                request.getFileServiceInfo());
         requestIntent.putExtra(MbmsDownloadManager.EXTRA_FD_COUNT, numFds);
         requestIntent.putExtra(MbmsDownloadManager.EXTRA_TEMP_FILE_ROOT,
                 mAppTempFileRoots.get(appKey));
@@ -219,14 +289,18 @@
                 break;
             }
             UriPathPair tempFile = tempFiles.get(i);
+            addTempFileInUse(appKey, request.getFileServiceInfo().getServiceId(),
+                    tempFile.getFilePathUri());
             FileInfo fileToDownload = filesToDownload.get(i);
             final boolean isLastFile = i == tempFiles.size() - 1;
             mHandler.postDelayed(() -> {
                 downloadSingleFile(appKey, request, tempFile, fileToDownload);
+                removeTempFileInUse(appKey, request.getFileServiceInfo().getServiceId(),
+                        tempFile.getFilePathUri());
                 if (isLastFile) {
                     mDoesAppHaveActiveDownload.put(appKey, false);
                 }
-            }, FILE_SEPARATION_DELAY * i);
+            }, FILE_SEPARATION_DELAY * i * mDownloadDelayFactor);
         }
     }
 
@@ -296,4 +370,30 @@
     private int getNumFdsNeededForRequest(DownloadRequest request) {
         return request.getFileServiceInfo().getFiles().size();
     }
+
+    private void addTempFileInUse(FrontendAppIdentifier appKey, String serviceId, Uri tempFileUri) {
+        Map<String, Set<Uri>> tempFileByService = mTempFilesInUse.get(appKey);
+        if (tempFileByService == null) {
+            tempFileByService = new ConcurrentHashMap<>();
+            mTempFilesInUse.put(appKey, tempFileByService);
+        }
+        Set<Uri> tempFilesInUse = tempFileByService.get(serviceId);
+        if (tempFilesInUse == null) {
+            tempFilesInUse = ConcurrentHashMap.newKeySet();
+            tempFileByService.put(serviceId, tempFilesInUse);
+        }
+        tempFilesInUse.add(tempFileUri);
+    }
+
+    private void removeTempFileInUse(FrontendAppIdentifier appKey, String serviceId,
+            Uri tempFileUri) {
+        Set<Uri> tempFilesInUse = mTempFilesInUse.getOrDefault(appKey, Collections.emptyMap())
+                .getOrDefault(serviceId, Collections.emptySet());
+        if (tempFilesInUse.contains(tempFileUri)) {
+            tempFilesInUse.remove(tempFileUri);
+        } else {
+            Log.w(LOG_TAG, "Trying to remove unknown temp file in use " + tempFileUri + " for app" +
+                    appKey + " and service id " + serviceId);
+        }
+    }
 }
diff --git a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/FileServiceRepository.java b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/FileServiceRepository.java
index 4d0b6c3..a771a1a 100644
--- a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/FileServiceRepository.java
+++ b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/FileServiceRepository.java
@@ -71,6 +71,10 @@
                 .collect(Collectors.toList());
     }
 
+    public List<FileServiceInfo> getAllFileServices() {
+        return new ArrayList<>(mIdToServiceInfo.values());
+    }
+
     public FileServiceInfo getFileServiceInfoForId(String serviceId) {
         return mIdToServiceInfo.getOrDefault(serviceId, null);
     }
diff --git a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/SideChannelReceiver.java b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/SideChannelReceiver.java
new file mode 100644
index 0000000..c9d38a0
--- /dev/null
+++ b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/SideChannelReceiver.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2017 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.phone.testapps.embmsmw;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.telephony.mbms.FileServiceInfo;
+import android.util.Log;
+
+/**
+ * Class for triggering artificial events from the frontend app. These would normally not come
+ * from the frontend app in a real embms implementation.
+ */
+public class SideChannelReceiver extends BroadcastReceiver {
+    public static final String ACTION_TRIGGER_CLEANUP =
+            "com.android.phone.testapps.embmsmw.TRIGGER_CLEANUP";
+    public static final String ACTION_REQUEST_SPURIOUS_TEMP_FILES =
+            "com.android.phone.testapps.embmsmw.REQUEST_SPURIOUS_TEMP_FILES";
+    public static final String ACTION_DELAY_DOWNLOAD =
+            "com.android.phone.testapps.embmsmw.DELAY_DOWNLOAD";
+
+    public static final String EXTRA_SERVICE_INFO =
+            "com.android.phone.testapps.embmsmw.SERVICE_INFO";
+    public static final String EXTRA_DELAY_FACTOR =
+            "com.android.phone.testapps.embmsmw.DELAY_FACTOR";
+
+    private static final String LOG_TAG = "EmbmsSampleMwSC";
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        EmbmsSampleDownloadService downloadService = EmbmsSampleDownloadService.getInstance();
+        if (downloadService == null) {
+            Log.w(LOG_TAG, "don't have instance of dl service");
+            return;
+        }
+        switch (intent.getAction()) {
+            case ACTION_TRIGGER_CLEANUP:
+                downloadService.requestCleanup();
+                break;
+            case ACTION_REQUEST_SPURIOUS_TEMP_FILES:
+                FileServiceInfo serviceInfo = intent.getParcelableExtra(EXTRA_SERVICE_INFO);
+                downloadService.requestExtraTempFiles(serviceInfo);
+                break;
+            case ACTION_DELAY_DOWNLOAD:
+                // Increase download latency by a certain factor
+                downloadService.delayDownloads(intent.getIntExtra(EXTRA_DELAY_FACTOR, 1));
+                break;
+
+        }
+    }
+}
diff --git a/testapps/EmbmsTestDownloadApp/res/layout/activity_main.xml b/testapps/EmbmsTestDownloadApp/res/layout/activity_main.xml
index 048e3dc..bee6b5d 100644
--- a/testapps/EmbmsTestDownloadApp/res/layout/activity_main.xml
+++ b/testapps/EmbmsTestDownloadApp/res/layout/activity_main.xml
@@ -32,37 +32,71 @@
         android:scrollbars="horizontal"
         android:horizontalSpacing="10dp"
         android:gravity="center"/>
-    <Button
-        android:id="@+id/bind_button"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:text="@string/bind_button" />
-    <Button
-        android:id="@+id/set_temp_root_button"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:text="@string/set_temp_root_button" />
-    <Button
-        android:id="@+id/get_file_services_button"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:text="@string/get_file_services_button" />
-    <Spinner
-        android:id="@+id/available_file_services"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"/>
-
-    <Button
-        android:id="@+id/request_dl_button"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:text="@string/request_dl_button" />
-
     <GridLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:columnCount="2"
         android:orientation="vertical" >
+        <Button
+            android:id="@+id/bind_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="0"
+            android:layout_column="0"
+            android:text="@string/bind_button" />
+        <Button
+            android:id="@+id/set_temp_root_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="0"
+            android:layout_column="1"
+            android:text="@string/set_temp_root_button" />
+        <Button
+            android:id="@+id/get_file_services_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="1"
+            android:layout_column="0"
+            android:text="@string/get_file_services_button" />
+        <Button
+            android:id="@+id/request_dl_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="1"
+            android:layout_column="1"
+            android:text="@string/request_dl_button" />
+        <Button
+            android:id="@+id/request_cleanup_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="2"
+            android:layout_column="0"
+            android:text="@string/request_cleanup_button" />
+        <Button
+            android:id="@+id/request_spurious_temp_files_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="2"
+            android:layout_column="1"
+            android:text="@string/request_spurious_temp_files_button" />
+        <Button
+            android:id="@+id/delay_download_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="3"
+            android:layout_column="0"
+            android:text="@string/delay_download_button" />
+        <NumberPicker
+            android:id="@+id/delay_factor"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_row="3"
+            android:layout_column="1"/>
     </GridLayout>
+
+    <Spinner
+        android:id="@+id/available_file_services"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"/>
 </LinearLayout>
diff --git a/testapps/EmbmsTestDownloadApp/res/values/donottranslate_strings.xml b/testapps/EmbmsTestDownloadApp/res/values/donottranslate_strings.xml
index 2d99962..7459591 100644
--- a/testapps/EmbmsTestDownloadApp/res/values/donottranslate_strings.xml
+++ b/testapps/EmbmsTestDownloadApp/res/values/donottranslate_strings.xml
@@ -20,4 +20,7 @@
     <string name="request_dl_button">Request DL</string>
     <string name="get_file_services_button">Fetch file services</string>
     <string name="set_temp_root_button">Set temp file root</string>
+    <string name="request_cleanup_button">Cleanup</string>
+    <string name="request_spurious_temp_files_button">Request more temp files</string>
+    <string name="delay_download_button">Delay download</string>
 </resources>
\ No newline at end of file
diff --git a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java
index 3937bbd..fd7deee 100644
--- a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java
+++ b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java
@@ -38,6 +38,7 @@
 import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.ImageView;
+import android.widget.NumberPicker;
 import android.widget.Spinner;
 import android.widget.TextView;
 import android.widget.Toast;
@@ -234,6 +235,25 @@
 
             performDownload(serviceInfo);
         });
+
+        Button requestCleanupButton = (Button) findViewById(R.id.request_cleanup_button);
+        requestCleanupButton.setOnClickListener((view) ->
+                SideChannel.triggerCleanup(EmbmsTestDownloadApp.this));
+
+        Button requestSpuriousTempFilesButton =
+                (Button) findViewById(R.id.request_spurious_temp_files_button);
+        requestSpuriousTempFilesButton.setOnClickListener((view) ->
+                SideChannel.requestSpuriousTempFiles(EmbmsTestDownloadApp.this,
+                        (FileServiceInfo) serviceSelector.getSelectedItem()));
+
+        NumberPicker downloadDelayPicker = (NumberPicker) findViewById(R.id.delay_factor);
+        downloadDelayPicker.setMinValue(1);
+        downloadDelayPicker.setMaxValue(50);
+
+        Button delayDownloadButton = (Button) findViewById(R.id.delay_download_button);
+        delayDownloadButton.setOnClickListener((view) ->
+                SideChannel.delayDownloads(EmbmsTestDownloadApp.this,
+                        downloadDelayPicker.getValue()));
     }
 
     @Override
@@ -270,12 +290,19 @@
 
     private void performDownload(FileServiceInfo info) {
         File destination = null;
+        Uri.Builder sourceUriBuilder = new Uri.Builder()
+                .scheme(FILE_DOWNLOAD_SCHEME)
+                .authority(FILE_AUTHORITY);
         try {
             if (info.getFiles().size() > 1) {
-                destination = new File(getFilesDir(), "images/").getCanonicalFile();
+                destination = new File(getFilesDir(), "images/animals/").getCanonicalFile();
                 destination.mkdirs();
+                clearDirectory(destination);
+                sourceUriBuilder.path("/*");
             } else {
                 destination = new File(getFilesDir(), "images/image.png").getCanonicalFile();
+                destination.delete();
+                sourceUriBuilder.path("/image.png");
             }
         } catch (IOException e) {
             // ignore
@@ -284,16 +311,10 @@
         Intent completionIntent = new Intent(DOWNLOAD_DONE_ACTION);
         completionIntent.setClass(this, DownloadCompletionReceiver.class);
 
-        Uri sourceUri = new Uri.Builder()
-                .scheme(FILE_DOWNLOAD_SCHEME)
-                .authority(FILE_AUTHORITY)
-                .path("/")
-                .build();
-
         DownloadRequest request = new DownloadRequest.Builder()
                 .setId(0)
                 .setServiceInfo(info)
-                .setSource(sourceUri)
+                .setSource(sourceUriBuilder.build())
                 .setDest(Uri.fromFile(destination))
                 .setAppIntent(completionIntent)
                 .setSubscriptionId(SubscriptionManager.getDefaultSubscriptionId())
@@ -305,6 +326,14 @@
             Toast.makeText(EmbmsTestDownloadApp.this,
                     "caught MbmsException: " + e.getErrorCode(), Toast.LENGTH_SHORT).show();
         }
+    }
 
+    private static void clearDirectory(File directory) {
+        for (File file: directory.listFiles()) {
+            if (file.isDirectory()) {
+                clearDirectory(file);
+            }
+            file.delete();
+        }
     }
 }
diff --git a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/SideChannel.java b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/SideChannel.java
new file mode 100644
index 0000000..6e7ebe9
--- /dev/null
+++ b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/SideChannel.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2017 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.phone.testapps.embmsdownload;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.telephony.mbms.FileServiceInfo;
+
+public class SideChannel {
+    public static final String ACTION_TRIGGER_CLEANUP =
+            "com.android.phone.testapps.embmsmw.TRIGGER_CLEANUP";
+    public static final String ACTION_REQUEST_SPURIOUS_TEMP_FILES =
+            "com.android.phone.testapps.embmsmw.REQUEST_SPURIOUS_TEMP_FILES";
+    public static final String ACTION_DELAY_DOWNLOAD =
+            "com.android.phone.testapps.embmsmw.DELAY_DOWNLOAD";
+
+    public static final String EXTRA_SERVICE_INFO =
+            "com.android.phone.testapps.embmsmw.SERVICE_INFO";
+    public static final String EXTRA_DELAY_FACTOR =
+            "com.android.phone.testapps.embmsmw.DELAY_FACTOR";
+
+    public static final ComponentName MIDDLEWARE_RECEIVER = new ComponentName(
+            "com.android.phone.testapps.embmsmw",
+            "com.android.phone.testapps.embmsmw.SideChannelReceiver");
+
+    public static void triggerCleanup(Context context) {
+        Intent intent  = new Intent(ACTION_TRIGGER_CLEANUP);
+        intent.setComponent(MIDDLEWARE_RECEIVER);
+        context.sendBroadcast(intent);
+    }
+
+    public static void requestSpuriousTempFiles(Context context, FileServiceInfo serviceInfo) {
+        Intent intent = new Intent(ACTION_REQUEST_SPURIOUS_TEMP_FILES);
+        intent.putExtra(EXTRA_SERVICE_INFO, serviceInfo);
+        intent.setComponent(MIDDLEWARE_RECEIVER);
+        context.sendBroadcast(intent);
+    }
+
+    public static void delayDownloads(Context context, int delay) {
+        Intent intent = new Intent(ACTION_DELAY_DOWNLOAD);
+        intent.putExtra(EXTRA_DELAY_FACTOR, delay);
+        intent.setComponent(MIDDLEWARE_RECEIVER);
+        context.sendBroadcast(intent);
+    }
+}