Merge changes from topic 'sort-order'

* changes:
  Migrate phone account sorting to use lamba expressions and add test.
  PhoneAccounts sorting
diff --git a/scripts/telecom_testing.sh b/scripts/telecom_testing.sh
index e6423a3..0ece427 100644
--- a/scripts/telecom_testing.sh
+++ b/scripts/telecom_testing.sh
@@ -1,6 +1,6 @@
-lite_test_telecom() {
+_lite_test_general() {
   usage="
-  Usage: lite_test_telecom [-c CLASSNAME] [-d] [-a | -i] [-e], where
+  Usage: $0 [-c CLASSNAME] [-d] [-a | -i] [-e], where
 
   -c CLASSNAME          Run tests only for the specified class/method. CLASSNAME
                           should be of the form SomeClassTest or SomeClassTest#testMethod.
@@ -15,12 +15,13 @@
 
   local OPTIND=1
   local class=
+  local project=
   local install=false
   local installwdep=false
   local debug=false
   local coverage=false
 
-  while getopts "c:hadie" opt; do
+  while getopts "c:p:hadie" opt; do
     case "$opt" in
       h)
         echo "$usage"
@@ -39,9 +40,28 @@
         installwdep=true;;
       e)
         coverage=true;;
+      p)
+        project=$OPTARG;;
     esac
   done
 
+  local build_dir=
+  local apk_loc=
+  local package_prefix=
+  local instrumentation=
+  case "$project" in
+    "telecom")
+      build_dir="packages/services/Telecomm/tests"
+      apk_loc="data/app/TelecomUnitTests/TelecomUnitTests.apk"
+      package_prefix="com.android.server.telecom.tests"
+      instrumentation="android.test.InstrumentationTestRunner";;
+    "telephony")
+      build_dir="frameworks/opt/telephony/tests/"
+      apk_loc="data/app/FrameworksTelephonyTests/FrameworksTelephonyTests.apk"
+      package_prefix="com.android.frameworks.telephonytests"
+      instrumentation="android.support.test.runner.AndroidJUnitRunner";;
+  esac
+
   local T=$(gettop)
 
   if [ $install = true ] ; then
@@ -57,9 +77,9 @@
     fi
 
     if [ $installwdep = true ] ; then
-      (export ${emma_opt}; mmma -j40 "packages/services/Telecomm/tests")
+      (export ${emma_opt}; mmma -j40 "$build_dir")
     else
-      (export ${emma_opt}; mmm "packages/services/Telecomm/tests")
+      (export ${emma_opt}; mmm "$build_dir")
     fi
     if [ $? -ne 0 ] ; then
       echo "Make failed! try using -a instead of -i if building with coverage"
@@ -69,7 +89,7 @@
     # Strip off any possible aosp_ prefix from the target product
     local canonical_product=$(sed 's/^aosp_//' <<< "$TARGET_PRODUCT")
 
-    adb install -r -t "out/target/product/$canonical_product/data/app/TelecomUnitTests/TelecomUnitTests.apk"
+    adb install -r -t "out/target/product/$canonical_product/$apk_loc"
     if [ $? -ne 0 ] ; then
       cd "$olddir"
       return $?
@@ -79,17 +99,22 @@
 
   local e_options=""
   if [ -n "$class" ] ; then
-    e_options="${e_options} -e class com.android.server.telecom.tests.${class}"
+    if [[ "$class" =~ "\." ]] ; then
+      e_options="${e_options} -e class ${class}"
+    else
+      e_options="${e_options} -e class ${package_prefix}.${class}"
+    fi
   fi
   if [ $debug = true ] ; then
     e_options="${e_options} -e debug 'true'"
   fi
-  if [ $coverage = true ] ; then
+  if [ $coverage = true ] && [ $project =~ "telecom" ] ; then
     e_options="${e_options} -e coverage 'true'"
   fi
-  adb shell am instrument ${e_options} -w com.android.server.telecom.tests/android.test.InstrumentationTestRunner
+  adb shell am instrument ${e_options} -w "$package_prefix/$instrumentation"
 
-  if [ $coverage = true ] ; then
+  # Code coverage only enabled for Telecom.
+  if [ $coverage = true ] && [ $project =~ "telecom" ] ; then
     adb root
     adb wait-for-device
     adb pull /data/user/0/com.android.server.telecom.tests/files/coverage.ec /tmp/
@@ -103,3 +128,11 @@
       --source-dir "$T/packages/services/Telecomm/src/"
   fi
 }
+
+lite_test_telecom() {
+  _lite_test_general -p telecom $@
+}
+
+lite_test_telephony() {
+  _lite_test_general -p telephony $@
+}
diff --git a/src/com/android/server/telecom/InCallController.java b/src/com/android/server/telecom/InCallController.java
index f74dc42..169ebd7 100644
--- a/src/com/android/server/telecom/InCallController.java
+++ b/src/com/android/server/telecom/InCallController.java
@@ -212,7 +212,8 @@
                 return CONNECTION_SUCCEEDED;
             }
 
-            if (call.isSelfManaged() && !mInCallServiceInfo.isSelfManagedCallsSupported()) {
+            if (call != null && call.isSelfManaged() &&
+                    !mInCallServiceInfo.isSelfManagedCallsSupported()) {
                 Log.i(this, "Skipping binding to %s - doesn't support self-mgd calls",
                         mInCallServiceInfo);
                 mIsConnected = false;
diff --git a/src/com/android/server/telecom/TelecomServiceImpl.java b/src/com/android/server/telecom/TelecomServiceImpl.java
index d4e1096..40ba21d 100644
--- a/src/com/android/server/telecom/TelecomServiceImpl.java
+++ b/src/com/android/server/telecom/TelecomServiceImpl.java
@@ -399,7 +399,12 @@
                             enforceRegisterMultiUser();
                         }
                         enforceUserHandleMatchesCaller(account.getAccountHandle());
-                        mPhoneAccountRegistrar.registerPhoneAccount(account);
+                        final long token = Binder.clearCallingIdentity();
+                        try {
+                            mPhoneAccountRegistrar.registerPhoneAccount(account);
+                        } finally {
+                            Binder.restoreCallingIdentity(token);
+                        }
                     } catch (Exception e) {
                         Log.e(this, e, "registerPhoneAccount %s", account);
                         throw e;
@@ -418,7 +423,12 @@
                     enforcePhoneAccountModificationForPackage(
                             accountHandle.getComponentName().getPackageName());
                     enforceUserHandleMatchesCaller(accountHandle);
-                    mPhoneAccountRegistrar.unregisterPhoneAccount(accountHandle);
+                    final long token = Binder.clearCallingIdentity();
+                    try {
+                        mPhoneAccountRegistrar.unregisterPhoneAccount(accountHandle);
+                    } finally {
+                        Binder.restoreCallingIdentity(token);
+                    }
                 } catch (Exception e) {
                     Log.e(this, e, "unregisterPhoneAccount %s", accountHandle);
                     throw e;
diff --git a/testapps/AndroidManifest.xml b/testapps/AndroidManifest.xml
index bfe8d0d..ba8db53 100644
--- a/testapps/AndroidManifest.xml
+++ b/testapps/AndroidManifest.xml
@@ -168,6 +168,16 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="com.android.server.telecom.testapps.TestUssdActivity"
+                android:label="@string/UssdUiAppLabel"
+                android:launchMode="singleInstance">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
         <activity android:name="com.android.server.telecom.testapps.SelfManagedCallingActivity"
                   android:label="@string/selfManagedCallingActivityLabel"
                   android:process="com.android.server.telecom.testapps.SelfMangingCallingApp"
diff --git a/testapps/res/layout/testussd_main.xml b/testapps/res/layout/testussd_main.xml
new file mode 100644
index 0000000..b4d67b0
--- /dev/null
+++ b/testapps/res/layout/testussd_main.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical" >
+    <EditText
+        android:id="@+id/number"
+        android:inputType="number"
+        android:layout_width="200dp"
+        android:layout_height="wrap_content" />
+    <Button
+        android:id="@+id/place_ussd_button"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/placeUssdButton" />
+</LinearLayout>
diff --git a/testapps/res/values/donottranslate_strings.xml b/testapps/res/values/donottranslate_strings.xml
index 9dc7cae..d4a011a 100644
--- a/testapps/res/values/donottranslate_strings.xml
+++ b/testapps/res/values/donottranslate_strings.xml
@@ -88,4 +88,7 @@
         <item>The FCC has mandated that I respond... I will do so begrudgingly</item>
         <item>😂😂😂💯</item>
     </string-array>
+
+    <string name="UssdUiAppLabel">Test Ussd UI</string>
+    <string name="placeUssdButton">Send USSD</string>
 </resources>
diff --git a/testapps/src/com/android/server/telecom/testapps/TestUssdActivity.java b/testapps/src/com/android/server/telecom/testapps/TestUssdActivity.java
new file mode 100644
index 0000000..3b1f4e9
--- /dev/null
+++ b/testapps/src/com/android/server/telecom/testapps/TestUssdActivity.java
@@ -0,0 +1,80 @@
+package com.android.server.telecom.testapps;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+import android.telephony.TelephonyManager;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.EditText;
+import android.widget.Toast;
+
+public class TestUssdActivity extends Activity {
+
+    private EditText mUssdNumberView;
+    private static Context context;
+    public static final String LOG_TAG = "TestUssdActivity";
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        TestUssdActivity.context = getApplicationContext();
+
+        setContentView(R.layout.testussd_main);
+        findViewById(R.id.place_ussd_button).setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+
+                placeUssdRequest();
+            }
+        });
+
+        mUssdNumberView = (EditText) findViewById(R.id.number);
+    }
+
+    public static final class OnReceiveUssdResponseCallback extends
+        TelephonyManager.OnReceiveUssdResponseCallback {
+
+            OnReceiveUssdResponseCallback() {
+            }
+
+            public void onReceiveUssdResponse(String req, CharSequence message) {
+                Log.i(LOG_TAG, "USSD Success:::" + req + "," + message);
+                showToast("USSD Response Successly received for code:" + req + "," + message);
+            }
+
+            public void onReceiveUssdResponseFailed(String req, int resultCode) {
+                Log.i(LOG_TAG, "USSD Fail:::" + req + "," + resultCode);
+                showToast("USSD Response failed for code:" + req + "," + resultCode);
+            }
+    }
+
+    private void placeUssdRequest() {
+
+        String mUssdNumber = mUssdNumberView.getText().toString();
+        if (mUssdNumber.equals("") || mUssdNumber == null) {
+            mUssdNumber = "932";
+        }
+        mUssdNumber = "#" + mUssdNumber + "#";
+        final TelephonyManager telephonyManager =
+                (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
+        try {
+            Handler h = new Handler(Looper.getMainLooper());
+            OnReceiveUssdResponseCallback receiveUssdResponseCallback =
+                    new OnReceiveUssdResponseCallback();
+
+            telephonyManager.sendUssdRequest(mUssdNumber, receiveUssdResponseCallback, h);
+
+        } catch (SecurityException e) {
+            showToast("Permission check failed");
+            return;
+        }
+    }
+
+    private static void showToast(String message) {
+        Toast.makeText(TestUssdActivity.context, message, Toast.LENGTH_SHORT).show();
+    }
+}
\ No newline at end of file
diff --git a/tests/src/com/android/server/telecom/tests/CallAudioRouteStateMachineTest.java b/tests/src/com/android/server/telecom/tests/CallAudioRouteStateMachineTest.java
index 14fdf05..95d6d51 100644
--- a/tests/src/com/android/server/telecom/tests/CallAudioRouteStateMachineTest.java
+++ b/tests/src/com/android/server/telecom/tests/CallAudioRouteStateMachineTest.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.media.AudioManager;
 import android.media.IAudioService;
+import android.os.Handler;
 import android.telecom.CallAudioState;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.MediumTest;
@@ -988,6 +989,8 @@
             verify(mMockInterruptionFilterProxy, never()).setInterruptionFilter(anyInt());
         }
 
+        Handler h = stateMachine.getHandler();
+        waitForHandlerAction(h, TEST_TIMEOUT);
         stateMachine.quitStateMachine();
 
         // Verify interactions with the speakerphone and bluetooth systems
diff --git a/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java b/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java
index fb4c118..bbfc11e 100644
--- a/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java
+++ b/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java
@@ -466,22 +466,10 @@
         if (shouldSucceed) {
             assertFalse(didExceptionOccur);
             verify(mFakePhoneAccountRegistrar).registerPhoneAccount(testPhoneAccount);
-            verify(mContext).sendBroadcastAsUser(intentCaptor.capture(), eq(UserHandle.ALL),
-                    anyString());
-
-            Intent capturedIntent = intentCaptor.getValue();
-            assertEquals(TelecomManager.ACTION_PHONE_ACCOUNT_REGISTERED,
-                    capturedIntent.getAction());
-            Bundle intentExtras = capturedIntent.getExtras();
-            assertEquals(1, intentExtras.size());
-            assertEquals(testPhoneAccount.getAccountHandle(),
-                    intentExtras.get(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE));
         } else {
             assertTrue(didExceptionOccur);
             verify(mFakePhoneAccountRegistrar, never())
                     .registerPhoneAccount(any(PhoneAccount.class));
-            verify(mContext, never())
-                    .sendBroadcastAsUser(any(Intent.class), any(UserHandle.class), anyString());
         }
     }
 
@@ -497,14 +485,6 @@
 
         mTSIBinder.unregisterPhoneAccount(phHandle);
         verify(mFakePhoneAccountRegistrar).unregisterPhoneAccount(phHandle);
-        verify(mContext).sendBroadcastAsUser(intentCaptor.capture(), eq(UserHandle.ALL),
-                anyString());
-        Intent capturedIntent = intentCaptor.getValue();
-        assertEquals(TelecomManager.ACTION_PHONE_ACCOUNT_UNREGISTERED,
-                capturedIntent.getAction());
-        Bundle intentExtras = capturedIntent.getExtras();
-        assertEquals(1, intentExtras.size());
-        assertEquals(phHandle, intentExtras.get(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE));
     }
 
     @SmallTest
diff --git a/tests/src/com/android/server/telecom/tests/TelecomSystemTest.java b/tests/src/com/android/server/telecom/tests/TelecomSystemTest.java
index c7cb941..1c81fec 100644
--- a/tests/src/com/android/server/telecom/tests/TelecomSystemTest.java
+++ b/tests/src/com/android/server/telecom/tests/TelecomSystemTest.java
@@ -25,6 +25,7 @@
 import static org.mockito.Matchers.eq;
 import static org.mockito.Matchers.isNull;
 import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.reset;
@@ -311,6 +312,7 @@
         super.setUp();
         mSpyContext = mComponentContextFixture.getTestDouble().getApplicationContext();
         doReturn(mSpyContext).when(mSpyContext).getApplicationContext();
+        doNothing().when(mSpyContext).sendBroadcastAsUser(any(), any(), any());
 
         mNumOutgoingCallsMade = 0;