Merge "Clarify AccountType.resPackageName/summaryResPackageName" into jb-dev
diff --git a/res/layout/contact_detail_add_connection_entry_view.xml b/res/layout/contact_detail_add_connection_entry_view.xml
new file mode 100644
index 0000000..208a8d4
--- /dev/null
+++ b/res/layout/contact_detail_add_connection_entry_view.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+ * Copyright 2012, 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.
+ */
+-->
+
+<FrameLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:paddingLeft="@dimen/detail_item_side_margin"
+    android:paddingRight="@dimen/detail_item_side_margin">
+    <LinearLayout
+        android:id="@+id/primary_action_view"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:paddingTop="@dimen/detail_item_vertical_margin"
+        android:paddingBottom="@dimen/detail_item_vertical_margin"
+        android:focusable="true"
+        android:background="?android:attr/selectableItemBackground"
+        android:minHeight="@dimen/detail_min_line_item_height"
+        android:orientation="horizontal"
+        android:gravity="center_vertical">
+
+        <ImageView
+            android:id="@+id/add_connection_icon"
+            android:layout_width="@dimen/detail_network_icon_size"
+            android:layout_height="@dimen/detail_network_icon_size"
+            android:layout_marginLeft="@dimen/detail_item_icon_margin"
+            android:layout_marginRight="@dimen/detail_item_icon_margin"
+            android:layout_gravity="center_vertical"
+            android:scaleType="centerInside" />
+
+        <TextView
+            android:id="@+id/add_connection_label"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:textAppearance="?android:attr/textAppearanceMedium"/>
+    </LinearLayout>
+</FrameLayout>
diff --git a/res/layout/contact_detail_network_title_entry_view.xml b/res/layout/contact_detail_network_title_entry_view.xml
index 1907a7a..09b8b34 100644
--- a/res/layout/contact_detail_network_title_entry_view.xml
+++ b/res/layout/contact_detail_network_title_entry_view.xml
@@ -49,6 +49,7 @@
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center_vertical"
-            android:textAppearance="?android:attr/textAppearanceMedium" />
+            android:textAppearance="?android:attr/textAppearanceMedium"
+            android:textColor="?android:attr/textColorSecondary" />
     </LinearLayout>
 </FrameLayout>
diff --git a/src/com/android/contacts/ContactSaveService.java b/src/com/android/contacts/ContactSaveService.java
index fdfd0f7..b8bf45f 100644
--- a/src/com/android/contacts/ContactSaveService.java
+++ b/src/com/android/contacts/ContactSaveService.java
@@ -506,6 +506,7 @@
                 }
             } finally {
                 outputStream.close();
+                photoFile.delete();
             }
         } catch (IOException e) {
             Log.e(TAG, "Failed to write photo: " + photoFile.toString() + " because: " + e);
diff --git a/src/com/android/contacts/activities/AttachPhotoActivity.java b/src/com/android/contacts/activities/AttachPhotoActivity.java
index 0ec0590..942f0be 100644
--- a/src/com/android/contacts/activities/AttachPhotoActivity.java
+++ b/src/com/android/contacts/activities/AttachPhotoActivity.java
@@ -80,7 +80,7 @@
             mTempPhotoUri = Uri.parse(icicle.getString(KEY_TEMP_PHOTO_URI));
             mTempPhotoFile = new File(mTempPhotoUri.getPath());
         } else {
-            mTempPhotoFile = ContactPhotoUtils.generateTempPhotoFile();
+            mTempPhotoFile = ContactPhotoUtils.generateTempPhotoFile(this);
             mTempPhotoUri = Uri.fromFile(mTempPhotoFile);
 
             Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
diff --git a/src/com/android/contacts/activities/PeopleActivity.java b/src/com/android/contacts/activities/PeopleActivity.java
index 1194a5e..bcceff4 100644
--- a/src/com/android/contacts/activities/PeopleActivity.java
+++ b/src/com/android/contacts/activities/PeopleActivity.java
@@ -150,7 +150,7 @@
 
     private ContactsUnavailableFragment mContactsUnavailableFragment;
     private ProviderStatusWatcher mProviderStatusWatcher;
-    private int mProviderStatus = -1;
+    private int mProviderStatus;
 
     private boolean mOptionsMenuContactsAvailable;
 
@@ -490,8 +490,6 @@
     @Override
     protected void onPause() {
         mOptionsMenuContactsAvailable = false;
-
-        mProviderStatus = -1;
         mProviderStatusWatcher.stop();
         super.onPause();
     }
@@ -499,8 +497,9 @@
     @Override
     protected void onResume() {
         super.onResume();
+
         mProviderStatusWatcher.start();
-        showContactsUnavailableFragmentIfNecessary();
+        updateViewConfiguration(true);
 
         // Re-register the listener, which may have been cleared when onSaveInstanceState was
         // called.  See also: onSaveInstanceState
@@ -983,15 +982,12 @@
 
     @Override
     public void onProviderStatusChange() {
-        showContactsUnavailableFragmentIfNecessary();
+        updateViewConfiguration(false);
     }
 
-    private void showContactsUnavailableFragmentIfNecessary() {
+    private void updateViewConfiguration(boolean forceUpdate) {
         int providerStatus = mProviderStatusWatcher.getProviderStatus();
-        if (providerStatus == mProviderStatus) {
-            return;
-        }
-
+        if (!forceUpdate && (providerStatus == mProviderStatus)) return;
         mProviderStatus = providerStatus;
 
         View contactsUnavailableView = findViewById(R.id.contacts_unavailable_view);
diff --git a/src/com/android/contacts/activities/PhotoSelectionActivity.java b/src/com/android/contacts/activities/PhotoSelectionActivity.java
index 509bd48..0610bb6 100644
--- a/src/com/android/contacts/activities/PhotoSelectionActivity.java
+++ b/src/com/android/contacts/activities/PhotoSelectionActivity.java
@@ -21,6 +21,7 @@
 import com.android.contacts.detail.PhotoSelectionHandler;
 import com.android.contacts.editor.PhotoActionPopup;
 import com.android.contacts.model.EntityDeltaList;
+import com.android.contacts.util.ContactPhotoUtils;
 import com.android.contacts.util.SchedulingUtils;
 
 import android.animation.Animator;
@@ -42,7 +43,6 @@
 import android.widget.FrameLayout.LayoutParams;
 import android.widget.ImageView;
 
-import java.io.File;
 
 /**
  * Popup activity for choosing a contact photo within the Contacts app.
@@ -60,6 +60,12 @@
     /** Number of ms for the animation to hide the backdrop on finish. */
     private static final int BACKDROP_FADEOUT_DURATION = 100;
 
+    /** Key used to persist photo-filename (NOT full file-path). */
+    private static final String KEY_CURRENT_PHOTO_FILE = "currentphotofile";
+
+    /** Key used to persist whether a sub-activity is currently in progress. */
+    private static final String KEY_SUB_ACTIVITY_IN_PROGRESS = "subinprogress";
+
     /** Intent extra to get the photo URI. */
     public static final String PHOTO_URI = "photo_uri";
 
@@ -132,14 +138,23 @@
     private boolean mCloseActivityWhenCameBackFromSubActivity;
 
     /**
+     * A photo result received by the activity, persisted across activity lifecycle.
+     */
+    private PendingPhotoResult mPendingPhotoResult;
+
+    /**
      * The photo file being interacted with, if any.  Saved/restored between activity instances.
      */
-    private File mCurrentPhotoFile;
+    private String mCurrentPhotoFile;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.photoselection_activity);
+        if (savedInstanceState != null) {
+            mCurrentPhotoFile = savedInstanceState.getString(KEY_CURRENT_PHOTO_FILE);
+            mSubActivityInProgress = savedInstanceState.getBoolean(KEY_SUB_ACTIVITY_IN_PROGRESS);
+        }
 
         // Pull data out of the intent.
         final Intent intent = getIntent();
@@ -395,11 +410,19 @@
     }
 
     @Override
+    protected void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putString(KEY_CURRENT_PHOTO_FILE, mCurrentPhotoFile);
+        outState.putBoolean(KEY_SUB_ACTIVITY_IN_PROGRESS, mSubActivityInProgress);
+    }
+
+    @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (mPhotoHandler != null) {
             mSubActivityInProgress = false;
             if (mPhotoHandler.handlePhotoActivityResult(requestCode, resultCode, data)) {
-                // Result was handled.  We'll get a callback later.
+                // Clear out any pending photo result.
+                mPendingPhotoResult = null;
             } else {
                 // User cancelled the sub-activity and returning to the photo selection activity.
                 if (mCloseActivityWhenCameBackFromSubActivity) {
@@ -410,8 +433,8 @@
                 }
             }
         } else {
-            // The result comes back before we prepare the handler?  This activity won't get
-            // re-created for orientation changes, so this shouldn't happen.
+            // Create a pending photo result to be handled when the photo handler is created.
+            mPendingPhotoResult = new PendingPhotoResult(requestCode, resultCode, data);
         }
     }
 
@@ -428,14 +451,20 @@
 
         mPhotoHandler = new PhotoHandler(this, mPhotoView, mode, mState);
 
-        // Setting the photo in displayPhoto() resulted in a relayout
-        // request... to avoid jank, wait until this layout has happened.
-        SchedulingUtils.doAfterLayout(mBackdrop, new Runnable() {
-            @Override
-            public void run() {
-                animatePhotoOpen();
-            }
-        });
+        if (mPendingPhotoResult != null) {
+            mPhotoHandler.handlePhotoActivityResult(mPendingPhotoResult.mRequestCode,
+                    mPendingPhotoResult.mResultCode, mPendingPhotoResult.mData);
+            mPendingPhotoResult = null;
+        } else {
+            // Setting the photo in displayPhoto() resulted in a relayout
+            // request... to avoid jank, wait until this layout has happened.
+            SchedulingUtils.doAfterLayout(mBackdrop, new Runnable() {
+                @Override
+                public void run() {
+                    animatePhotoOpen();
+                }
+            });
+        }
     }
 
     private final class PhotoHandler extends PhotoSelectionHandler {
@@ -454,27 +483,27 @@
         }
 
         @Override
-        public void startPhotoActivity(Intent intent, int requestCode, File photoFile) {
+        public void startPhotoActivity(Intent intent, int requestCode, String photoFile) {
             mSubActivityInProgress = true;
             mCurrentPhotoFile = photoFile;
             PhotoSelectionActivity.this.startActivityForResult(intent, requestCode);
         }
 
         private final class PhotoListener extends PhotoActionListener {
-
             @Override
             public void onPhotoSelected(Bitmap bitmap) {
                 EntityDeltaList delta = getDeltaForAttachingPhotoToContact();
                 long rawContactId = getWritableEntityId();
-                String filePath = mCurrentPhotoFile.getAbsolutePath();
+                final String croppedPath = ContactPhotoUtils.pathForCroppedPhoto(
+                        PhotoSelectionActivity.this, mCurrentPhotoFile);
                 Intent intent = ContactSaveService.createSaveContactIntent(
-                        mContext, delta, "", 0, mIsProfile, null, null, rawContactId, filePath);
+                        mContext, delta, "", 0, mIsProfile, null, null, rawContactId, croppedPath);
                 startService(intent);
                 finish();
             }
 
             @Override
-            public File getCurrentPhotoFile() {
+            public String getCurrentPhotoFile() {
                 return mCurrentPhotoFile;
             }
 
@@ -486,4 +515,15 @@
             }
         }
     }
+
+    private static class PendingPhotoResult {
+        final private int mRequestCode;
+        final private int mResultCode;
+        final private Intent mData;
+        private PendingPhotoResult(int requestCode, int resultCode, Intent data) {
+            mRequestCode = requestCode;
+            mResultCode = resultCode;
+            mData = data;
+        }
+    }
 }
diff --git a/src/com/android/contacts/detail/ContactDetailFragment.java b/src/com/android/contacts/detail/ContactDetailFragment.java
index 06852d2..c3ccfa2 100644
--- a/src/com/android/contacts/detail/ContactDetailFragment.java
+++ b/src/com/android/contacts/detail/ContactDetailFragment.java
@@ -811,7 +811,7 @@
         for (AccountType accountType : mOtherEntriesMap.keySet()) {
 
             // Add a title for each third party app
-            mAllEntries.add(NetworkTitleViewEntry.fromAccountType(mContext, accountType));
+            mAllEntries.add(new NetworkTitleViewEntry(mContext, accountType));
 
             for (DetailViewEntry detailEntry : mOtherEntriesMap.get(accountType)) {
                 // Add indented separator
@@ -867,7 +867,7 @@
         };
 
         // Finally create the entry.
-        mAllEntries.add(NetworkTitleViewEntry.forMoreNetworks(mContext, onClickListener));
+        mAllEntries.add(new AddConnectionViewEntry(mContext, onClickListener));
     }
 
     /**
@@ -1124,35 +1124,43 @@
     }
 
     /**
-     * A title for a section of contact details from a single 3rd party network.  It's also
-     * used for the "More networks" entry, which has the same layout.
+     * A title for a section of contact details from a single 3rd party network.
      */
     private static class NetworkTitleViewEntry extends ViewEntry {
         private final Drawable mIcon;
         private final CharSequence mLabel;
-        private final View.OnClickListener mOnClickListener;
 
-        private NetworkTitleViewEntry(Drawable icon, CharSequence label, View.OnClickListener
-                onClickListener) {
+        public NetworkTitleViewEntry(Context context, AccountType type) {
             super(ViewAdapter.VIEW_TYPE_NETWORK_TITLE_ENTRY);
-            this.mIcon = icon;
-            this.mLabel = label;
-            this.mOnClickListener = onClickListener;
+            this.mIcon = type.getDisplayIcon(context);
+            this.mLabel = type.getDisplayLabel(context);
             this.isEnabled = false;
         }
 
-        public static NetworkTitleViewEntry fromAccountType(Context context, AccountType type) {
-            return new NetworkTitleViewEntry(
-                    type.getDisplayIcon(context), type.getDisplayLabel(context), null);
+        public Drawable getIcon() {
+            return mIcon;
         }
 
-        public static NetworkTitleViewEntry forMoreNetworks(Context context, View.OnClickListener
-                onClickListener) {
-            // TODO Icon is temporary.  Need proper one.
-            return new NetworkTitleViewEntry(
-                    context.getResources().getDrawable(R.drawable.ic_menu_add_field_holo_light),
-                    context.getString(R.string.add_connection_button),
-                    onClickListener);
+        public CharSequence getLabel() {
+            return mLabel;
+        }
+    }
+
+    /**
+     * This is used for the "Add Connections" entry.
+     */
+    private static class AddConnectionViewEntry extends ViewEntry {
+        private final Drawable mIcon;
+        private final CharSequence mLabel;
+        private final View.OnClickListener mOnClickListener;
+
+        private AddConnectionViewEntry(Context context, View.OnClickListener onClickListener) {
+            super(ViewAdapter.VIEW_TYPE_ADD_CONNECTION_ENTRY);
+            this.mIcon = context.getResources().getDrawable(
+                    R.drawable.ic_menu_add_field_holo_light);
+            this.mLabel = context.getString(R.string.add_connection_button);
+            this.mOnClickListener = onClickListener;
+            this.isEnabled = true;
         }
 
         @Override
@@ -1347,6 +1355,14 @@
         }
     }
 
+    private static class KindTitleViewCache {
+        public final TextView titleView;
+
+        public KindTitleViewCache(View view) {
+            titleView = (TextView)view.findViewById(R.id.title);
+        }
+    }
+
     /**
      * Cache of the children views for a view that displays a {@link NetworkTitleViewEntry}
      */
@@ -1361,6 +1377,21 @@
     }
 
     /**
+     * Cache of the children views for a view that displays a {@link AddConnectionViewEntry}
+     */
+    private static class AddConnectionViewCache {
+        public final TextView name;
+        public final ImageView icon;
+        public final View primaryActionView;
+
+        public AddConnectionViewCache(View view) {
+            name = (TextView) view.findViewById(R.id.add_connection_label);
+            icon = (ImageView) view.findViewById(R.id.add_connection_icon);
+            primaryActionView = view.findViewById(R.id.primary_action_view);
+        }
+    }
+
+    /**
      * Cache of the children views of a contact detail entry represented by a
      * {@link DetailViewEntry}
      */
@@ -1404,8 +1435,9 @@
         public static final int VIEW_TYPE_HEADER_ENTRY = 1;
         public static final int VIEW_TYPE_KIND_TITLE_ENTRY = 2;
         public static final int VIEW_TYPE_NETWORK_TITLE_ENTRY = 3;
-        public static final int VIEW_TYPE_SEPARATOR_ENTRY = 4;
-        private static final int VIEW_TYPE_COUNT = 5;
+        public static final int VIEW_TYPE_ADD_CONNECTION_ENTRY = 4;
+        public static final int VIEW_TYPE_SEPARATOR_ENTRY = 5;
+        private static final int VIEW_TYPE_COUNT = 6;
 
         @Override
         public View getView(int position, View convertView, ViewGroup parent) {
@@ -1420,6 +1452,8 @@
                     return getDetailEntryView(position, convertView, parent);
                 case VIEW_TYPE_NETWORK_TITLE_ENTRY:
                     return getNetworkTitleEntryView(position, convertView, parent);
+                case VIEW_TYPE_ADD_CONNECTION_ENTRY:
+                    return getAddConnectionEntryView(position, convertView, parent);
                 default:
                     throw new IllegalStateException("Invalid view type ID " +
                             getItemViewType(position));
@@ -1517,11 +1551,19 @@
 
         private View getKindTitleEntryView(int position, View convertView, ViewGroup parent) {
             final KindTitleViewEntry entry = (KindTitleViewEntry) getItem(position);
+            final View result;
+            final KindTitleViewCache viewCache;
 
-            final View result = (convertView != null) ? convertView :
-                    mInflater.inflate(R.layout.list_separator, parent, false);
-            final TextView titleTextView = (TextView) result.findViewById(R.id.title);
-            titleTextView.setText(entry.getTitle());
+            if (convertView != null) {
+                result = convertView;
+                viewCache = (KindTitleViewCache)result.getTag();
+            } else {
+                result = mInflater.inflate(R.layout.list_separator, parent, false);
+                viewCache = new KindTitleViewCache(result);
+                result.setTag(viewCache);
+            }
+
+            viewCache.titleView.setText(entry.getTitle());
 
             return result;
         }
@@ -1539,8 +1581,6 @@
                         parent, false);
                 viewCache = new NetworkTitleViewCache(result);
                 result.setTag(viewCache);
-                result.findViewById(R.id.primary_action_view).setOnClickListener(
-                        entry.mOnClickListener);
             }
 
             viewCache.name.setText(entry.getLabel());
@@ -1549,6 +1589,27 @@
             return result;
         }
 
+        private View getAddConnectionEntryView(int position, View convertView, ViewGroup parent) {
+            final AddConnectionViewEntry entry = (AddConnectionViewEntry) getItem(position);
+            final View result;
+            final AddConnectionViewCache viewCache;
+
+            if (convertView != null) {
+                result = convertView;
+                viewCache = (AddConnectionViewCache) result.getTag();
+            } else {
+                result = mInflater.inflate(R.layout.contact_detail_add_connection_entry_view,
+                        parent, false);
+                viewCache = new AddConnectionViewCache(result);
+                result.setTag(viewCache);
+            }
+            viewCache.name.setText(entry.getLabel());
+            viewCache.icon.setImageDrawable(entry.getIcon());
+            viewCache.primaryActionView.setOnClickListener(entry.mOnClickListener);
+
+            return result;
+        }
+
         private View getDetailEntryView(int position, View convertView, ViewGroup parent) {
             final DetailViewEntry entry = (DetailViewEntry) getItem(position);
             final View v;
diff --git a/src/com/android/contacts/detail/PhotoSelectionHandler.java b/src/com/android/contacts/detail/PhotoSelectionHandler.java
index e11a054..73296a6 100644
--- a/src/com/android/contacts/detail/PhotoSelectionHandler.java
+++ b/src/com/android/contacts/detail/PhotoSelectionHandler.java
@@ -115,12 +115,15 @@
         final PhotoActionListener listener = getListener();
         if (resultCode == Activity.RESULT_OK) {
             switch (requestCode) {
+                // Photo was chosen (either new or existing from gallery), and cropped.
                 case REQUEST_CODE_PHOTO_PICKED_WITH_DATA: {
-                    Bitmap bitmap = BitmapFactory.decodeFile(
-                            listener.getCurrentPhotoFile().getAbsolutePath());
+                    final String path = ContactPhotoUtils.pathForCroppedPhoto(
+                            mContext, listener.getCurrentPhotoFile());
+                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                     listener.onPhotoSelected(bitmap);
                     return true;
                 }
+                // Photo was successfully taken, now crop it.
                 case REQUEST_CODE_CAMERA_WITH_DATA: {
                     doCropPhoto(listener.getCurrentPhotoFile());
                     return true;
@@ -183,23 +186,28 @@
     }
 
     /** Used by subclasses to delegate to their enclosing Activity or Fragment. */
-    protected abstract void startPhotoActivity(Intent intent, int requestCode, File photoFile);
+    protected abstract void startPhotoActivity(Intent intent, int requestCode, String photoFile);
 
     /**
      * Sends a newly acquired photo to Gallery for cropping
      */
-    private void doCropPhoto(File f) {
+    private void doCropPhoto(String fileName) {
         try {
+            // Obtain the absolute paths for the newly-taken photo, and the destination
+            // for the soon-to-be-cropped photo.
+            final String newPath = ContactPhotoUtils.pathForNewCameraPhoto(fileName);
+            final String croppedPath = ContactPhotoUtils.pathForCroppedPhoto(mContext, fileName);
+
             // Add the image to the media store
             MediaScannerConnection.scanFile(
                     mContext,
-                    new String[] { f.getAbsolutePath() },
+                    new String[] { newPath },
                     new String[] { null },
                     null);
 
             // Launch gallery to crop the photo
-            final Intent intent = getCropImageIntent(f);
-            startPhotoActivity(intent, REQUEST_CODE_PHOTO_PICKED_WITH_DATA, f);
+            final Intent intent = getCropImageIntent(newPath, croppedPath);
+            startPhotoActivity(intent, REQUEST_CODE_PHOTO_PICKED_WITH_DATA, fileName);
         } catch (Exception e) {
             Log.e(TAG, "Cannot crop image", e);
             Toast.makeText(mContext, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
@@ -212,7 +220,7 @@
      *     what should be returned by
      *     {@link PhotoSelectionHandler.PhotoActionListener#getCurrentPhotoFile()}.
      */
-    private void startTakePhotoActivity(File photoFile) {
+    private void startTakePhotoActivity(String photoFile) {
         final Intent intent = getTakePhotoIntent(photoFile);
         startPhotoActivity(intent, REQUEST_CODE_CAMERA_WITH_DATA, photoFile);
     }
@@ -223,7 +231,7 @@
      *     stored by the content-provider.
      *     {@link PhotoSelectionHandler#handlePhotoActivityResult(int, int, Intent)}.
      */
-    private void startPickFromGalleryActivity(File photoFile) {
+    private void startPickFromGalleryActivity(String photoFile) {
         final Intent intent = getPhotoPickIntent(photoFile);
         startPhotoActivity(intent, REQUEST_CODE_PHOTO_PICKED_WITH_DATA, photoFile);
     }
@@ -243,41 +251,44 @@
     /**
      * Constructs an intent for picking a photo from Gallery, cropping it and returning the bitmap.
      */
-    private Intent getPhotoPickIntent(File photoFile) {
-        Uri photoUri = Uri.fromFile(photoFile);
-        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
+    private Intent getPhotoPickIntent(String photoFile) {
+        final String croppedPhotoPath = ContactPhotoUtils.pathForCroppedPhoto(mContext, photoFile);
+        final Uri croppedPhotoUri = Uri.fromFile(new File(croppedPhotoPath));
+        final Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
         intent.setType("image/*");
         intent.putExtra("crop", "true");
         intent.putExtra("aspectX", 1);
         intent.putExtra("aspectY", 1);
         intent.putExtra("outputX", mPhotoPickSize);
         intent.putExtra("outputY", mPhotoPickSize);
-        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
+        intent.putExtra(MediaStore.EXTRA_OUTPUT, croppedPhotoUri);
         return intent;
     }
 
     /**
      * Constructs an intent for image cropping.
      */
-    private Intent getCropImageIntent(File photoFile) {
-        Uri photoUri = Uri.fromFile(photoFile);
+    private Intent getCropImageIntent(String inputPhotoPath, String croppedPhotoPath) {
+        final Uri inputPhotoUri = Uri.fromFile(new File(inputPhotoPath));
+        final Uri croppedPhotoUri = Uri.fromFile(new File(croppedPhotoPath));
         Intent intent = new Intent("com.android.camera.action.CROP");
-        intent.setDataAndType(photoUri, "image/*");
+        intent.setDataAndType(inputPhotoUri, "image/*");
         intent.putExtra("crop", "true");
         intent.putExtra("aspectX", 1);
         intent.putExtra("aspectY", 1);
         intent.putExtra("outputX", mPhotoPickSize);
         intent.putExtra("outputY", mPhotoPickSize);
-        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
+        intent.putExtra(MediaStore.EXTRA_OUTPUT, croppedPhotoUri);
         return intent;
     }
 
     /**
      * Constructs an intent for capturing a photo and storing it in a temporary file.
      */
-    public static Intent getTakePhotoIntent(File f) {
+    private static Intent getTakePhotoIntent(String fileName) {
         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
-        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
+        final String newPhotoPath = ContactPhotoUtils.pathForNewCameraPhoto(fileName);
+        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(newPhotoPath)));
         return intent;
     }
 
@@ -296,10 +307,10 @@
         public void onTakePhotoChosen() {
             try {
                 // Launch camera to take photo for selected contact
-                startTakePhotoActivity(ContactPhotoUtils.generateTempPhotoFile());
+                startTakePhotoActivity(ContactPhotoUtils.generateTempPhotoFileName());
             } catch (ActivityNotFoundException e) {
-                Toast.makeText(mContext, R.string.photoPickerNotFoundText,
-                        Toast.LENGTH_LONG).show();
+                Toast.makeText(
+                        mContext, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
             }
         }
 
@@ -307,10 +318,10 @@
         public void onPickFromGalleryChosen() {
             try {
                 // Launch picker to choose photo for selected contact
-                startPickFromGalleryActivity(ContactPhotoUtils.generateTempPhotoFile());
+                startPickFromGalleryActivity(ContactPhotoUtils.generateTempPhotoFileName());
             } catch (ActivityNotFoundException e) {
-                Toast.makeText(mContext, R.string.photoPickerNotFoundText,
-                        Toast.LENGTH_LONG).show();
+                Toast.makeText(
+                        mContext, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
             }
         }
 
@@ -325,7 +336,7 @@
          * fragment's responsibility to maintain this in saved state, since this handler instance
          * will not survive rotation.
          */
-        public abstract File getCurrentPhotoFile();
+        public abstract String getCurrentPhotoFile();
 
         /**
          * Called when the photo selection dialog is dismissed.
diff --git a/src/com/android/contacts/editor/ContactEditorFragment.java b/src/com/android/contacts/editor/ContactEditorFragment.java
index 7d9f510..cd9d98b 100644
--- a/src/com/android/contacts/editor/ContactEditorFragment.java
+++ b/src/com/android/contacts/editor/ContactEditorFragment.java
@@ -23,6 +23,7 @@
 import com.android.contacts.activities.ContactEditorAccountsChangedActivity;
 import com.android.contacts.activities.ContactEditorActivity;
 import com.android.contacts.activities.JoinContactActivity;
+import com.android.contacts.activities.PhotoSelectionActivity;
 import com.android.contacts.detail.PhotoSelectionHandler;
 import com.android.contacts.editor.AggregationSuggestionEngine.Suggestion;
 import com.android.contacts.editor.Editor.EditorListener;
@@ -35,6 +36,7 @@
 import com.android.contacts.model.EntityModifier;
 import com.android.contacts.model.GoogleAccountType;
 import com.android.contacts.util.AccountsListAdapter;
+import com.android.contacts.util.ContactPhotoUtils;
 import com.android.contacts.util.AccountsListAdapter.AccountListFilter;
 import com.android.contacts.util.HelpUtils;
 
@@ -195,7 +197,7 @@
 
     private Cursor mGroupMetaData;
 
-    private File mCurrentPhotoFile;
+    private String mCurrentPhotoFile;
     private Bundle mUpdatedPhotos = new Bundle();
 
     private Context mContext;
@@ -410,10 +412,7 @@
             mRawContactIdRequestingPhoto = savedState.getLong(
                     KEY_RAW_CONTACT_ID_REQUESTING_PHOTO);
             mViewIdGenerator = savedState.getParcelable(KEY_VIEW_ID_GENERATOR);
-            String fileName = savedState.getString(KEY_CURRENT_PHOTO_FILE);
-            if (fileName != null) {
-                mCurrentPhotoFile = new File(fileName);
-            }
+            mCurrentPhotoFile = savedState.getString(KEY_CURRENT_PHOTO_FILE);
             mContactIdForJoin = savedState.getLong(KEY_CONTACT_ID_FOR_JOIN);
             mContactWritableForJoin = savedState.getBoolean(KEY_CONTACT_WRITABLE_FOR_JOIN);
             mAggregationSuggestionsRawContactId = savedState.getLong(KEY_SHOW_JOIN_SUGGESTIONS);
@@ -918,10 +917,10 @@
         // help menu depending on whether this is inserting or editing
         if (Intent.ACTION_INSERT.equals(mAction)) {
             // inserting
-            HelpUtils.prepareHelpMenuItem(getActivity(), helpMenu, R.string.help_url_people_add);
+            HelpUtils.prepareHelpMenuItem(mContext, helpMenu, R.string.help_url_people_add);
         } else if (Intent.ACTION_EDIT.equals(mAction)) {
             // editing
-            HelpUtils.prepareHelpMenuItem(getActivity(), helpMenu, R.string.help_url_people_edit);
+            HelpUtils.prepareHelpMenuItem(mContext, helpMenu, R.string.help_url_people_edit);
         } else {
             // something else, so don't show the help menu
             helpMenu.setVisible(false);
@@ -966,7 +965,7 @@
         // If we just started creating a new contact and haven't added any data, it's too
         // early to do a join
         if (mState.size() == 1 && mState.get(0).isContactInsert() && !hasPendingChanges()) {
-            Toast.makeText(getActivity(), R.string.toast_join_with_empty_contact,
+            Toast.makeText(mContext, R.string.toast_join_with_empty_contact,
                             Toast.LENGTH_LONG).show();
             return true;
         }
@@ -1024,10 +1023,11 @@
         saveDefaultAccountIfNecessary();
 
         // Save contact
-        Intent intent = ContactSaveService.createSaveContactIntent(getActivity(), mState,
-                SAVE_MODE_EXTRA_KEY, saveMode, isEditingUserProfile(), getActivity().getClass(),
-                ContactEditorActivity.ACTION_SAVE_COMPLETED, mUpdatedPhotos);
-        getActivity().startService(intent);
+        Intent intent = ContactSaveService.createSaveContactIntent(mContext, mState,
+                SAVE_MODE_EXTRA_KEY, saveMode, isEditingUserProfile(),
+                ((Activity)mContext).getClass(), ContactEditorActivity.ACTION_SAVE_COMPLETED,
+                mUpdatedPhotos);
+        mContext.startService(intent);
 
         // Don't try to save the same photos twice.
         mUpdatedPhotos = new Bundle();
@@ -1543,9 +1543,7 @@
 
         outState.putLong(KEY_RAW_CONTACT_ID_REQUESTING_PHOTO, mRawContactIdRequestingPhoto);
         outState.putParcelable(KEY_VIEW_ID_GENERATOR, mViewIdGenerator);
-        if (mCurrentPhotoFile != null) {
-            outState.putString(KEY_CURRENT_PHOTO_FILE, mCurrentPhotoFile.toString());
-        }
+        outState.putString(KEY_CURRENT_PHOTO_FILE, mCurrentPhotoFile);
         outState.putLong(KEY_CONTACT_ID_FOR_JOIN, mContactIdForJoin);
         outState.putBoolean(KEY_CONTACT_WRITABLE_FOR_JOIN, mContactWritableForJoin);
         outState.putLong(KEY_SHOW_JOIN_SUGGESTIONS, mAggregationSuggestionsRawContactId);
@@ -1606,7 +1604,7 @@
     /**
      * Sets the photo stored in mPhoto and writes it to the RawContact with the given id
      */
-    private void setPhoto(long rawContact, Bitmap photo, File photoFile) {
+    private void setPhoto(long rawContact, Bitmap photo, String photoFile) {
         BaseRawContactEditorView requestingEditor = getRawContactEditorView(rawContact);
 
         if (photo == null || photo.getHeight() < 0 || photo.getWidth() < 0) {
@@ -1620,7 +1618,9 @@
             Log.w(TAG, "The contact that requested the photo is no longer present.");
         }
 
-        mUpdatedPhotos.putString(String.valueOf(rawContact), photoFile.getAbsolutePath());
+        final String croppedPhotoPath =
+                ContactPhotoUtils.pathForCroppedPhoto(mContext, mCurrentPhotoFile);
+        mUpdatedPhotos.putString(String.valueOf(rawContact), croppedPhotoPath);
     }
 
     /**
@@ -1757,7 +1757,7 @@
         }
 
         @Override
-        public void startPhotoActivity(Intent intent, int requestCode, File photoFile) {
+        public void startPhotoActivity(Intent intent, int requestCode, String photoFile) {
             mRawContactIdRequestingPhoto = mEditor.getRawContactId();
             mStatus = Status.SUB_ACTIVITY;
             mCurrentPhotoFile = photoFile;
@@ -1819,7 +1819,7 @@
             }
 
             @Override
-            public File getCurrentPhotoFile() {
+            public String getCurrentPhotoFile() {
                 return mCurrentPhotoFile;
             }
 
diff --git a/src/com/android/contacts/util/ContactPhotoUtils.java b/src/com/android/contacts/util/ContactPhotoUtils.java
index f214e9f..2bd8e80 100644
--- a/src/com/android/contacts/util/ContactPhotoUtils.java
+++ b/src/com/android/contacts/util/ContactPhotoUtils.java
@@ -17,6 +17,7 @@
 
 package com.android.contacts.util;
 
+import android.content.Context;
 import android.graphics.Bitmap;
 import android.os.Environment;
 import android.util.Log;
@@ -35,11 +36,9 @@
     private static final String TAG = "ContactPhotoUtils";
 
     private static final String PHOTO_DATE_FORMAT = "'IMG'_yyyyMMdd_HHmmss";
+    private static final String NEW_PHOTO_DIR_PATH =
+            Environment.getExternalStorageDirectory() + "/DCIM/Camera";
 
-    // TODO: /DCIM/Camera isn't the ideal place to stash cropped contact photos.
-    //       Where is the right place?
-    private static final File PHOTO_DIR = new File(
-            Environment.getExternalStorageDirectory() + "/DCIM/Camera");
 
     /**
      * Generate a new, unique file to be used as an out-of-band communication
@@ -47,15 +46,28 @@
      * This file will be passed to other activities (such as the gallery/camera/cropper/etc.),
      * and read by us once they are finished writing it.
      */
-    public static File generateTempPhotoFile() {
-        PHOTO_DIR.mkdirs();
-        return new File(PHOTO_DIR, generateTempPhotoFileName());
+    public static File generateTempPhotoFile(Context context) {
+        return new File(pathForCroppedPhoto(context, generateTempPhotoFileName()));
     }
 
-    private static String generateTempPhotoFileName() {
+    public static String pathForCroppedPhoto(Context context, String fileName) {
+        final File dir = new File(context.getExternalCacheDir() + "/tmp");
+        dir.mkdirs();
+        final File f = new File(dir, fileName);
+        return f.getAbsolutePath();
+    }
+
+    public static String pathForNewCameraPhoto(String fileName) {
+        final File dir = new File(NEW_PHOTO_DIR_PATH);
+        dir.mkdirs();
+        final File f = new File(dir, fileName);
+        return f.getAbsolutePath();
+    }
+
+    public static String generateTempPhotoFileName() {
         Date date = new Date(System.currentTimeMillis());
         SimpleDateFormat dateFormat = new SimpleDateFormat(PHOTO_DATE_FORMAT);
-        return dateFormat.format(date) + ".jpg";
+        return "ContactPhoto-" + dateFormat.format(date) + ".jpg";
     }
 
     /**