Move Pbap permission dialog to Settings app.

Strings and diglog are removed and will reappear and modified in Settings
app. We want phone AT commander to use the dialog too.
bug 4489572

Change-Id: I0283b5deff974e53384dc5a92bd01c02e12bbcd6
diff --git a/android/app/AndroidManifest.xml b/android/app/AndroidManifest.xml
index bbba0df..846d169 100644
--- a/android/app/AndroidManifest.xml
+++ b/android/app/AndroidManifest.xml
@@ -136,6 +136,8 @@
             android:name=".pbap.BluetoothPbapReceiver">
             <intent-filter>
                 <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
+                <action android:name="android.bluetooth.device.action.CONNECTION_ACCESS_REPLY" />
+                <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </receiver>
     </application>
diff --git a/android/app/res/layout/access.xml b/android/app/res/layout/access.xml
deleted file mode 100644
index d9abd53..0000000
--- a/android/app/res/layout/access.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2009, 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.
-*/
--->
-
-<ScrollView
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_height="match_parent"
-    android:layout_width="match_parent">
-
-    <LinearLayout
-        android:layout_height="match_parent"
-        android:layout_width="match_parent"
-        android:orientation="vertical">
-
-        <TextView
-            android:id="@+id/message"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_marginLeft="20dip"
-            android:layout_marginRight="20dip"
-            android:gravity="center_horizontal"
-            android:textAppearance="?android:attr/textAppearanceMedium" />
-
-        <CheckBox android:id="@+id/alwaysallowed"
-            style="?android:attr/textAppearanceMedium"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_marginTop="2dip"
-            android:text="@string/alwaysallowed" />
-
-    </LinearLayout>
-
-</ScrollView>
diff --git a/android/app/res/values/strings_pbap.xml b/android/app/res/values/strings_pbap.xml
index 4dd145d..cddd3f7 100644
--- a/android/app/res/values/strings_pbap.xml
+++ b/android/app/res/values/strings_pbap.xml
@@ -1,22 +1,14 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="pbap_acceptance_dialog_title">%1$s would like to access your contacts and call history. Give access to %2$s?</string>
-    <string name="pbap_acceptance_dialog_header">Phonebook Access</string>
     <string name="pbap_session_key_dialog_title">Type session key for %1$s</string>
     <string name="pbap_session_key_dialog_header">Bluetooth session key required</string>
     <string name="pbap_acceptance_timeout_message">There was time out to accept connection with %1$s</string>
     <string name="pbap_authentication_timeout_message">There was time out to input session key with %1$s</string>
-    <string name="pbap_notif_ticker">Phonebook access request</string>
-    <!-- Notification title when a Bluetooth device wants to pair with us -->
-    <string name="pbap_notif_title">PBAP request</string>
-    <!-- Notification message when a Bluetooth device wants to pair with us -->
-    <string name="pbap_notif_message">Allow phonebook access by %1$s</string>
     <string name="auth_notif_ticker">Obex authentication request</string>
     <!-- Notification title when a Bluetooth device wants to pair with us -->
     <string name="auth_notif_title">Session Key</string>
     <!-- Notification message when a Bluetooth device wants to pair with us -->
     <string name="auth_notif_message">Type session key for %1$s</string>
-    <string name="alwaysallowed">Always allowed?</string>
     <string name="defaultname">Carkit</string>
     <string name="unknownName">Unknown name</string>
     <string name="localPhoneName">My name</string>
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java
index 42e99d4..0bcd981 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java
@@ -71,9 +71,7 @@
 
     private static final int BLUETOOTH_OBEX_AUTHKEY_MAX_LENGTH = 16;
 
-    private static final int DIALOG_YES_NO_CONNECT = 1;
-
-    private static final int DIALOG_YES_NO_AUTH = 2;
+    private static final int DIALOG_YES_NO_AUTH = 1;
 
     private static final String KEY_USER_TIMEOUT = "user_timeout";
 
@@ -114,10 +112,7 @@
         super.onCreate(savedInstanceState);
         Intent i = getIntent();
         String action = i.getAction();
-        if (action.equals(BluetoothPbapService.ACCESS_REQUEST_ACTION)) {
-            showPbapDialog(DIALOG_YES_NO_CONNECT);
-            mCurrentDialog = DIALOG_YES_NO_CONNECT;
-        } else if (action.equals(BluetoothPbapService.AUTH_CHALL_ACTION)) {
+        if (action.equals(BluetoothPbapService.AUTH_CHALL_ACTION)) {
             showPbapDialog(DIALOG_YES_NO_AUTH);
             mCurrentDialog = DIALOG_YES_NO_AUTH;
         } else {
@@ -132,17 +127,6 @@
     private void showPbapDialog(int id) {
         final AlertController.AlertParams p = mAlertParams;
         switch (id) {
-            case DIALOG_YES_NO_CONNECT:
-                p.mIconId = android.R.drawable.ic_dialog_info;
-                p.mTitle = getString(R.string.pbap_acceptance_dialog_header);
-                p.mView = createView(DIALOG_YES_NO_CONNECT);
-                p.mPositiveButtonText = getString(android.R.string.yes);
-                p.mPositiveButtonListener = this;
-                p.mNegativeButtonText = getString(android.R.string.no);
-                p.mNegativeButtonListener = this;
-                mOkButton = mAlert.getButton(DialogInterface.BUTTON_POSITIVE);
-                setupAlert();
-                break;
             case DIALOG_YES_NO_AUTH:
                 p.mIconId = android.R.drawable.ic_dialog_info;
                 p.mTitle = getString(R.string.pbap_session_key_dialog_header);
@@ -163,10 +147,6 @@
     private String createDisplayText(final int id) {
         String mRemoteName = BluetoothPbapService.getRemoteDeviceName();
         switch (id) {
-            case DIALOG_YES_NO_CONNECT:
-                String mMessage1 = getString(R.string.pbap_acceptance_dialog_title, mRemoteName,
-                        mRemoteName);
-                return mMessage1;
             case DIALOG_YES_NO_AUTH:
                 String mMessage2 = getString(R.string.pbap_session_key_dialog_title, mRemoteName);
                 return mMessage2;
@@ -177,22 +157,6 @@
 
     private View createView(final int id) {
         switch (id) {
-            case DIALOG_YES_NO_CONNECT:
-                mView = getLayoutInflater().inflate(R.layout.access, null);
-                messageView = (TextView)mView.findViewById(R.id.message);
-                messageView.setText(createDisplayText(id));
-                mAlwaysAllowed = (CheckBox)mView.findViewById(R.id.alwaysallowed);
-                mAlwaysAllowed.setChecked(true);
-                mAlwaysAllowed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
-                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-                        if (isChecked) {
-                            mAlwaysAllowedValue = true;
-                        } else {
-                            mAlwaysAllowedValue = false;
-                        }
-                    }
-                });
-                return mView;
             case DIALOG_YES_NO_AUTH:
                 mView = getLayoutInflater().inflate(R.layout.auth, null);
                 messageView = (TextView)mView.findViewById(R.id.message);
@@ -210,10 +174,7 @@
 
     private void onPositive() {
         if (!mTimeout) {
-            if (mCurrentDialog == DIALOG_YES_NO_CONNECT) {
-                sendIntentToReceiver(BluetoothPbapService.ACCESS_ALLOWED_ACTION,
-                        BluetoothPbapService.EXTRA_ALWAYS_ALLOWED, mAlwaysAllowedValue);
-            } else if (mCurrentDialog == DIALOG_YES_NO_AUTH) {
+            if (mCurrentDialog == DIALOG_YES_NO_AUTH) {
                 sendIntentToReceiver(BluetoothPbapService.AUTH_RESPONSE_ACTION,
                         BluetoothPbapService.EXTRA_SESSION_KEY, mSessionKey);
                 mKeyView.removeTextChangedListener(this);
@@ -224,9 +185,7 @@
     }
 
     private void onNegative() {
-        if (mCurrentDialog == DIALOG_YES_NO_CONNECT) {
-            sendIntentToReceiver(BluetoothPbapService.ACCESS_DISALLOWED_ACTION, null, null);
-        } else if (mCurrentDialog == DIALOG_YES_NO_AUTH) {
+        if (mCurrentDialog == DIALOG_YES_NO_AUTH) {
             sendIntentToReceiver(BluetoothPbapService.AUTH_CANCELLED_ACTION, null, null);
             mKeyView.removeTextChangedListener(this);
         }
@@ -274,13 +233,7 @@
 
     private void onTimeout() {
         mTimeout = true;
-        if (mCurrentDialog == DIALOG_YES_NO_CONNECT) {
-            messageView.setText(getString(R.string.pbap_acceptance_timeout_message,
-                    BluetoothPbapService.getRemoteDeviceName()));
-            mAlert.getButton(DialogInterface.BUTTON_NEGATIVE).setVisibility(View.GONE);
-            mAlwaysAllowed.setVisibility(View.GONE);
-            mAlwaysAllowed.clearFocus();
-        } else if (mCurrentDialog == DIALOG_YES_NO_AUTH) {
+        if (mCurrentDialog == DIALOG_YES_NO_AUTH) {
             messageView.setText(getString(R.string.pbap_authentication_timeout_message,
                     BluetoothPbapService.getRemoteDeviceName()));
             mKeyView.setVisibility(View.GONE);
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
index 0cd6951..f82137a 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
@@ -76,25 +76,6 @@
     public static final boolean VERBOSE = false;
 
     /**
-     * Intent indicating incoming connection request which is sent to
-     * BluetoothPbapActivity
-     */
-    public static final String ACCESS_REQUEST_ACTION = "com.android.bluetooth.pbap.accessrequest";
-
-    /**
-     * Intent indicating incoming connection request accepted by user which is
-     * sent from BluetoothPbapActivity
-     */
-    public static final String ACCESS_ALLOWED_ACTION = "com.android.bluetooth.pbap.accessallowed";
-
-    /**
-     * Intent indicating incoming connection request denied by user which is
-     * sent from BluetoothPbapActivity
-     */
-    public static final String ACCESS_DISALLOWED_ACTION =
-            "com.android.bluetooth.pbap.accessdisallowed";
-
-    /**
      * Intent indicating incoming obex authentication request which is from
      * PCE(Carkit)
      */
@@ -120,12 +101,6 @@
             "com.android.bluetooth.pbap.userconfirmtimeout";
 
     /**
-     * Intent Extra name indicating always allowed which is sent from
-     * BluetoothPbapActivity
-     */
-    public static final String EXTRA_ALWAYS_ALLOWED = "com.android.bluetooth.pbap.alwaysallowed";
-
-    /**
      * Intent Extra name indicating session key which is sent from
      * BluetoothPbapActivity
      */
@@ -196,6 +171,13 @@
 
     private IBluetooth mBluetoothService;
 
+    private boolean isWaitingAuthorization = false;
+
+    // package and class name to which we send intent to check phone book access permission
+    private static final String ACCESS_AUTHORITY_PACKAGE = "com.android.settings";
+    private static final String ACCESS_AUTHORITY_CLASS =
+        "com.android.settings.bluetooth.BluetoothPermissionRequest";
+
     public BluetoothPbapService() {
         mState = BluetoothPbap.STATE_DISCONNECTED;
         IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE);
@@ -258,31 +240,44 @@
             if (state == BluetoothAdapter.STATE_OFF) {
                 // Send any pending timeout now, as this service will be destroyed.
                 if (mSessionStatusHandler.hasMessages(USER_TIMEOUT)) {
-                    Intent timeoutIntent = new Intent(USER_CONFIRM_TIMEOUT_ACTION);
+                    Intent timeoutIntent =
+                        new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL);
+                    timeoutIntent.setClassName(ACCESS_AUTHORITY_PACKAGE, ACCESS_AUTHORITY_CLASS);
                     sendBroadcast(timeoutIntent);
-                    removePbapNotification(NOTIFICATION_ID_ACCESS);
                 }
                 // Release all resources
                 closeService();
             } else {
                 removeTimeoutMsg = false;
             }
-        } else if (action.equals(ACCESS_ALLOWED_ACTION)) {
-            if (intent.getBooleanExtra(EXTRA_ALWAYS_ALLOWED, false)) {
-                boolean result = mRemoteDevice.setTrust(true);
-                if (VERBOSE) Log.v(TAG, "setTrust() result=" + result);
+        } else if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY)) {
+            if (!isWaitingAuthorization) {
+                // this reply is not for us
+                return;
             }
-            try {
-                if (mConnSocket != null) {
-                    startObexServerSession();
-                } else {
-                    stopObexServerSession();
+
+            isWaitingAuthorization = false;
+
+            if (intent.getIntExtra(BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT,
+                                   BluetoothDevice.CONNECTION_ACCESS_NO) ==
+                BluetoothDevice.CONNECTION_ACCESS_YES) {
+
+                if (intent.getBooleanExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, false)) {
+                    boolean result = mRemoteDevice.setTrust(true);
+                    if (VERBOSE) Log.v(TAG, "setTrust() result=" + result);
                 }
-            } catch (IOException ex) {
-                Log.e(TAG, "Caught the error: " + ex.toString());
+                try {
+                    if (mConnSocket != null) {
+                        startObexServerSession();
+                    } else {
+                        stopObexServerSession();
+                    }
+                } catch (IOException ex) {
+                    Log.e(TAG, "Caught the error: " + ex.toString());
+                }
+            } else {
+                stopObexServerSession();
             }
-        } else if (action.equals(ACCESS_DISALLOWED_ACTION)) {
-            stopObexServerSession();
         } else if (action.equals(AUTH_RESPONSE_ACTION)) {
             String sessionkey = intent.getStringExtra(EXTRA_SESSION_KEY);
             notifyAuthKeyInput(sessionkey);
@@ -541,8 +536,19 @@
                                     + ex.toString());
                         }
                     } else {
-                        createPbapNotification(ACCESS_REQUEST_ACTION);
-                        if (VERBOSE) Log.v(TAG, "incomming connection accepted from: "
+                        Intent intent = new
+                            Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST);
+                        intent.setClassName(ACCESS_AUTHORITY_PACKAGE, ACCESS_AUTHORITY_CLASS);
+                        intent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
+                                        BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS);
+                        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mRemoteDevice);
+                        intent.putExtra(BluetoothDevice.EXTRA_PACKAGE_NAME, getPackageName());
+                        intent.putExtra(BluetoothDevice.EXTRA_CLASS_NAME,
+                                        BluetoothPbapReceiver.class.getName());
+                        sendBroadcast(intent, BLUETOOTH_PERM);
+                        isWaitingAuthorization = true;
+
+                        if (VERBOSE) Log.v(TAG, "waiting for authorization for connection from: "
                                 + sRemoteDeviceName);
 
                         // In case car kit time out and try to use HFP for
@@ -582,9 +588,10 @@
                     }
                     break;
                 case USER_TIMEOUT:
-                    Intent intent = new Intent(USER_CONFIRM_TIMEOUT_ACTION);
+                    Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL);
+                    intent.setClassName(ACCESS_AUTHORITY_PACKAGE, ACCESS_AUTHORITY_CLASS);
                     sendBroadcast(intent);
-                    removePbapNotification(NOTIFICATION_ID_ACCESS);
+                    isWaitingAuthorization = false;
                     stopObexServerSession();
                     break;
                 case AUTH_TIMEOUT:
@@ -653,20 +660,7 @@
         Notification notification = null;
         String name = getRemoteDeviceName();
 
-        if (action.equals(ACCESS_REQUEST_ACTION)) {
-            deleteIntent.setAction(ACCESS_DISALLOWED_ACTION);
-            notification = new Notification(android.R.drawable.stat_sys_data_bluetooth,
-                getString(R.string.pbap_notif_ticker), System.currentTimeMillis());
-            notification.setLatestEventInfo(this, getString(R.string.pbap_notif_title),
-                    getString(R.string.pbap_notif_message, name), PendingIntent
-                            .getActivity(this, 0, clickIntent, 0));
-
-            notification.flags |= Notification.FLAG_AUTO_CANCEL;
-            notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
-            notification.defaults = Notification.DEFAULT_SOUND;
-            notification.deleteIntent = PendingIntent.getBroadcast(this, 0, deleteIntent, 0);
-            nm.notify(NOTIFICATION_ID_ACCESS, notification);
-        } else if (action.equals(AUTH_CHALL_ACTION)) {
+        if (action.equals(AUTH_CHALL_ACTION)) {
             deleteIntent.setAction(AUTH_CANCELLED_ACTION);
             notification = new Notification(android.R.drawable.stat_sys_data_bluetooth,
                 getString(R.string.auth_notif_ticker), System.currentTimeMillis());