Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 0bea517d authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge changes from topics 'sim-tests', 'import-notification' into ub-contactsdialer-i-dev

* changes:
  Add additional tests of SIM contact importing
  DO NOT MERGE Improve testability of SIM import code.
  DO NOT MERGE Add notification for SIM import
parents bb15fabb a75206b1
Loading
Loading
Loading
Loading
+5 −0
Original line number Diff line number Diff line
@@ -394,6 +394,11 @@
            android:name=".ContactSaveService"
            android:exported="false" />

         <!-- Service to import contacts from the SIM card -->
         <service
             android:name=".SimImportService"
             android:exported="false" />

        <!-- Attaches a photo to a contact. Started from external applications -->
        <activity android:name=".activities.AttachPhotoActivity"
            android:label="@string/attach_photo_dialog_title"
+9 −0
Original line number Diff line number Diff line
@@ -1904,4 +1904,13 @@
         [CHAR LIMIT=NONE] -->
    <string name="show_more_content_description">Show more</string>

    <!-- The notification title shown when importing a SIM card finishes [CHAR LIMIT=40] -->
    <string name="importing_sim_finished_title">Finished importing SIM card</string>

    <!-- Notification title shown when importing SIM contacts failed [CHAR LIMIT=40] -->
    <string name="importing_sim_failed_title">Couldn\'t import SIM card</string>

    <!-- The notification title shown while SIM contacts are being imported [CHAR LIMIT=40] -->
    <string name="importing_sim_in_progress_title">Importing SIM</string>

</resources>
+2 −66
Original line number Diff line number Diff line
@@ -16,8 +16,6 @@

package com.android.contacts;

import static android.Manifest.permission.WRITE_CONTACTS;

import android.app.Activity;
import android.app.IntentService;
import android.content.ContentProviderOperation;
@@ -49,7 +47,6 @@ import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContactsEntity;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.os.ResultReceiver;
import android.telephony.SubscriptionInfo;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
@@ -63,8 +60,6 @@ import com.android.contacts.common.model.CPOWrapper;
import com.android.contacts.common.model.RawContactDelta;
import com.android.contacts.common.model.RawContactDeltaList;
import com.android.contacts.common.model.RawContactModifier;
import com.android.contacts.common.model.SimCard;
import com.android.contacts.common.model.SimContact;
import com.android.contacts.common.model.account.AccountWithDataSet;
import com.android.contacts.common.preference.ContactsPreferences;
import com.android.contacts.common.util.ContactDisplayUtils;
@@ -72,7 +67,6 @@ import com.android.contacts.common.util.PermissionsUtil;
import com.android.contacts.compat.PinnedPositionsCompat;
import com.android.contacts.util.ContactPhotoUtils;
import com.android.contactsbind.FeedbackHelper;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

@@ -82,6 +76,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static android.Manifest.permission.WRITE_CONTACTS;

/**
 * A service responsible for saving changes to the content provider.
 */
@@ -149,16 +145,11 @@ public class ContactSaveService extends IntentService {
    public static final String EXTRA_UNDO_ACTION = "undoAction";
    public static final String EXTRA_UNDO_DATA = "undoData";

    public static final String ACTION_IMPORT_FROM_SIM = "importFromSim";
    public static final String EXTRA_SIM_CONTACTS = "simContacts";
    public static final String EXTRA_SIM_SUBSCRIPTION_ID = "simSubscriptionId";

    // For debugging and testing what happens when requests are queued up.
    public static final String ACTION_SLEEP = "sleep";
    public static final String EXTRA_SLEEP_DURATION = "sleepDuration";

    public static final String BROADCAST_GROUP_DELETED = "groupDeleted";
    public static final String BROADCAST_SIM_IMPORT_COMPLETE = "simImportComplete";
    public static final String BROADCAST_LINK_COMPLETE = "linkComplete";
    public static final String BROADCAST_UNLINK_COMPLETE = "unlinkComplete";

@@ -166,7 +157,6 @@ public class ContactSaveService extends IntentService {

    public static final String EXTRA_RESULT_CODE = "resultCode";
    public static final String EXTRA_RESULT_COUNT = "count";
    public static final String EXTRA_OPERATION_REQUESTED_AT_TIME = "requestedTime";

    public static final int CP2_ERROR = 0;
    public static final int CONTACTS_LINKED = 1;
@@ -361,8 +351,6 @@ public class ContactSaveService extends IntentService {
            setRingtone(intent);
        } else if (ACTION_UNDO.equals(action)) {
            undo(intent);
        } else if (ACTION_IMPORT_FROM_SIM.equals(action)) {
            importFromSim(intent);
        } else if (ACTION_SLEEP.equals(action)) {
            sleepForDebugging(intent);
        }
@@ -1751,58 +1739,6 @@ public class ContactSaveService extends IntentService {
        operations.add(builder.build());
    }

    /**
     * Returns an intent that can be used to import the contacts into targetAccount.
     *
     * @param context context to use for creating the intent
     * @param subscriptionId the subscriptionId of the SIM card that is being imported. See
     *                       {@link SubscriptionInfo#getSubscriptionId()}. Upon completion the
     *                       SIM for that subscription ID will be marked as imported
     * @param contacts the contacts to import
     * @param targetAccount the account import the contacts into
     */
    public static Intent createImportFromSimIntent(Context context, int subscriptionId,
            ArrayList<SimContact> contacts, AccountWithDataSet targetAccount) {
        return new Intent(context, ContactSaveService.class)
                .setAction(ACTION_IMPORT_FROM_SIM)
                .putExtra(EXTRA_SIM_CONTACTS, contacts)
                .putExtra(EXTRA_SIM_SUBSCRIPTION_ID, subscriptionId)
                .putExtra(EXTRA_ACCOUNT, targetAccount);
    }

    private void importFromSim(Intent intent) {
        final Intent result = new Intent(BROADCAST_SIM_IMPORT_COMPLETE)
                .putExtra(EXTRA_OPERATION_REQUESTED_AT_TIME, System.currentTimeMillis());
        final int subscriptionId = intent.getIntExtra(EXTRA_SIM_SUBSCRIPTION_ID,
                SimCard.NO_SUBSCRIPTION_ID);
        try {
            final AccountWithDataSet targetAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
            final ArrayList<SimContact> contacts =
                    intent.getParcelableArrayListExtra(EXTRA_SIM_CONTACTS);
            mSimContactDao.importContacts(contacts, targetAccount);

            // Update the imported state of the SIM card that was imported
            final SimCard sim = mSimContactDao.getSimBySubscriptionId(subscriptionId);
            if (sim != null) {
                mSimContactDao.persistSimState(sim.withImportedState(true));
            }

            // notify success
            LocalBroadcastManager.getInstance(this).sendBroadcast(result
                    .putExtra(EXTRA_RESULT_COUNT, contacts.size())
                    .putExtra(EXTRA_RESULT_CODE, RESULT_SUCCESS)
                    .putExtra(EXTRA_SIM_SUBSCRIPTION_ID, subscriptionId));
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "importFromSim completed successfully");
            }
        } catch (RemoteException|OperationApplicationException e) {
            FeedbackHelper.sendFeedback(this, TAG, "Failed to import contacts from SIM card", e);
            LocalBroadcastManager.getInstance(this).sendBroadcast(result
                    .putExtra(EXTRA_RESULT_CODE, RESULT_FAILURE)
                    .putExtra(EXTRA_SIM_SUBSCRIPTION_ID, subscriptionId));
        }
    }

    /**
     * Returns an intent that can start this service and cause it to sleep for the specified time.
     *
+2 −4
Original line number Diff line number Diff line
@@ -281,10 +281,8 @@ public class SimImportFragment extends Fragment
                importableContacts.add(mAdapter.getItem(checked.keyAt(i)));
            }
        }
        ContactSaveService.startService(getContext(), ContactSaveService
                .createImportFromSimIntent(getContext(), mSubscriptionId,
                        importableContacts,
                        mAccountHeaderPresenter.getCurrentAccount()));
        SimImportService.startImport(getContext(), mSubscriptionId, importableContacts,
                mAccountHeaderPresenter.getCurrentAccount());
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+341 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2016 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.contacts;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.TimingLogger;

import com.android.contacts.activities.PeopleActivity;
import com.android.contacts.common.database.SimContactDao;
import com.android.contacts.common.database.SimContactDaoImpl;
import com.android.contacts.common.model.SimCard;
import com.android.contacts.common.model.SimContact;
import com.android.contacts.common.model.account.AccountWithDataSet;
import com.android.contactsbind.FeedbackHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Imports {@link SimContact}s from a background thread
 */
public class SimImportService extends Service {

    private static final String TAG = "SimImportService";

    /**
     * Wrapper around the service state for testability
     */
    public interface StatusProvider {

        /**
         * Returns whether there is any imports still pending
         *
         * <p>This should be called from the UI thread</p>
         */
        boolean isRunning();

        /**
         * Returns whether an import for sim has been requested
         *
         * <p>This should be called from the UI thread</p>
         */
        boolean isImporting(SimCard sim);
    }

    public static final String EXTRA_ACCOUNT = "account";
    public static final String EXTRA_SIM_CONTACTS = "simContacts";
    public static final String EXTRA_SIM_SUBSCRIPTION_ID = "simSubscriptionId";
    public static final String EXTRA_RESULT_CODE = "resultCode";
    public static final String EXTRA_RESULT_COUNT = "count";
    public static final String EXTRA_OPERATION_REQUESTED_AT_TIME = "requestedTime";

    public static final String BROADCAST_SERVICE_STATE_CHANGED =
            SimImportService.class.getName() + "#serviceStateChanged";
    public static final String BROADCAST_SIM_IMPORT_COMPLETE =
            SimImportService.class.getName() + "#simImportComplete";

    public static final int RESULT_UNKNOWN = 0;
    public static final int RESULT_SUCCESS = 1;
    public static final int RESULT_FAILURE = 2;

    // VCardService uses jobIds for it's notifications which count up from 0 so we just use a
    // bigger number to prevent overlap.
    private static final int NOTIFICATION_ID = 100;

    private ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    // Keeps track of current tasks. This is only modified from the UI thread.
    private static List<ImportTask> sPending = new ArrayList<>();

    private static StatusProvider sStatusProvider = new StatusProvider() {
        @Override
        public boolean isRunning() {
            return !sPending.isEmpty();
        }

        @Override
        public boolean isImporting(SimCard sim) {
            return SimImportService.isImporting(sim);
        }
    };

    /**
     * Returns whether an import for sim has been requested
     *
     * <p>This should be called from the UI thread</p>
     */
    private static boolean isImporting(SimCard sim) {
        for (ImportTask task : sPending) {
            if (task.getSim().equals(sim)) {
                return true;
            }
        }
        return false;
    }

    public static StatusProvider getStatusProvider() {
        return sStatusProvider;
    }

    /**
     * Starts an import of the contacts from the sim into the target account
     *
     * @param context context to use for starting the service
     * @param subscriptionId the subscriptionId of the SIM card that is being imported. See
     *                       {@link android.telephony.SubscriptionInfo#getSubscriptionId()}.
     *                       Upon completion the SIM for that subscription ID will be marked as
     *                       imported
     * @param contacts the contacts to import
     * @param targetAccount the account import the contacts into
     */
    public static void startImport(Context context, int subscriptionId,
            ArrayList<SimContact> contacts, AccountWithDataSet targetAccount) {
        context.startService(new Intent(context, SimImportService.class)
                .putExtra(EXTRA_SIM_CONTACTS, contacts)
                .putExtra(EXTRA_SIM_SUBSCRIPTION_ID, subscriptionId)
                .putExtra(EXTRA_ACCOUNT, targetAccount));
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, final int startId) {
        final ImportTask task = createTaskForIntent(intent, startId);
        if (task == null) {
            new StopTask(this, startId).executeOnExecutor(mExecutor);
            return START_NOT_STICKY;
        }
        sPending.add(task);
        task.executeOnExecutor(mExecutor);
        notifyStateChanged();
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mExecutor.shutdown();
    }

    private ImportTask createTaskForIntent(Intent intent, int startId) {
        final AccountWithDataSet targetAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
        final ArrayList<SimContact> contacts =
                intent.getParcelableArrayListExtra(EXTRA_SIM_CONTACTS);

        final int subscriptionId = intent.getIntExtra(EXTRA_SIM_SUBSCRIPTION_ID,
                SimCard.NO_SUBSCRIPTION_ID);
        final SimContactDao dao = SimContactDao.create(this);
        final SimCard sim = dao.getSimBySubscriptionId(subscriptionId);
        if (sim != null) {
            return new ImportTask(sim, contacts, targetAccount, dao, startId);
        } else {
            return null;
        }
    }

    private Notification getCompletedNotification() {
        final Intent intent = new Intent(this, PeopleActivity.class);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setOngoing(false)
                .setAutoCancel(true)
                .setContentTitle(this.getString(R.string.importing_sim_finished_title))
                .setColor(this.getResources().getColor(R.color.dialtacts_theme_color))
                .setSmallIcon(R.drawable.ic_check_mark)
                .setContentIntent(PendingIntent.getActivity(this, 0, intent, 0));
        return builder.build();
    }

    private Notification getFailedNotification() {
        final Intent intent = new Intent(this, PeopleActivity.class);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setOngoing(false)
                .setAutoCancel(true)
                .setContentTitle(this.getString(R.string.importing_sim_failed_title))
                .setColor(this.getResources().getColor(R.color.dialtacts_theme_color))
                .setSmallIcon(R.drawable.ic_check_mark)
                .setContentIntent(PendingIntent.getActivity(this, 0, intent, 0));
        return builder.build();
    }

    private Notification getImportingNotification() {
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        final String description = getString(R.string.importing_sim_in_progress_title);
        builder.setOngoing(true)
                .setProgress(/* current */ 0, /* max */ 100, /* indeterminate */ true)
                .setContentTitle(description)
                .setColor(this.getResources().getColor(R.color.dialtacts_theme_color))
                .setSmallIcon(android.R.drawable.stat_sys_download);
        return builder.build();
    }

    private void notifyStateChanged() {
        LocalBroadcastManager.getInstance(this).sendBroadcast(
                new Intent(BROADCAST_SERVICE_STATE_CHANGED));
    }

    // Schedule a task that calls stopSelf when it completes. This is used to ensure that the
    // calls to stopSelf occur in the correct order (because this service uses a single thread
    // executor this won't run until all work that was requested before it has finished)
    private static class StopTask extends AsyncTask<Void, Void, Void> {
        private Service mHost;
        private final int mStartId;

        private StopTask(Service host, int startId) {
            mHost = host;
            mStartId = startId;
        }

        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            mHost.stopSelf(mStartId);
        }
    }

    private class ImportTask extends AsyncTask<Void, Void, Boolean> {
        private final SimCard mSim;
        private final List<SimContact> mContacts;
        private final AccountWithDataSet mTargetAccount;
        private final SimContactDao mDao;
        private final NotificationManager mNotificationManager;
        private final int mStartId;
        private final long mStartTime;

        public ImportTask(SimCard sim, List<SimContact> contacts, AccountWithDataSet targetAccount,
                SimContactDao dao, int startId) {
            mSim = sim;
            mContacts = contacts;
            mTargetAccount = targetAccount;
            mDao = dao;
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mStartId = startId;
            mStartTime = System.currentTimeMillis();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            startForeground(NOTIFICATION_ID, getImportingNotification());
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            final TimingLogger timer = new TimingLogger(TAG, "import");
            try {
                // Just import them all at once.
                // Experimented with using smaller batches (e.g. 25 and 50) so that percentage
                // progress could be displayed however this slowed down the import by over a factor
                // of 2. If the batch size is over a 100 then most cases will only require a single
                // batch so we don't even worry about displaying accurate progress
                mDao.importContacts(mContacts, mTargetAccount);
                mDao.persistSimState(mSim.withImportedState(true));
                timer.addSplit("done");
                timer.dumpToLog();
            } catch (RemoteException|OperationApplicationException e) {
                FeedbackHelper.sendFeedback(SimImportService.this, TAG,
                        "Failed to import contacts from SIM card", e);
                return false;
            }
            return true;
        }

        public SimCard getSim() {
            return mSim;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            stopSelf(mStartId);

            Intent result;
            final Notification notification;
            if (success) {
                result = new Intent(BROADCAST_SIM_IMPORT_COMPLETE)
                        .putExtra(EXTRA_RESULT_CODE, RESULT_SUCCESS)
                        .putExtra(EXTRA_RESULT_COUNT, mContacts.size())
                        .putExtra(EXTRA_OPERATION_REQUESTED_AT_TIME, mStartTime)
                        .putExtra(EXTRA_SIM_SUBSCRIPTION_ID, mSim.getSubscriptionId());

                notification = getCompletedNotification();
            } else {
                result = new Intent(BROADCAST_SIM_IMPORT_COMPLETE)
                        .putExtra(EXTRA_RESULT_CODE, RESULT_FAILURE)
                        .putExtra(EXTRA_OPERATION_REQUESTED_AT_TIME, mStartTime)
                        .putExtra(EXTRA_SIM_SUBSCRIPTION_ID, mSim.getSubscriptionId());

                notification = getFailedNotification();
            }
            LocalBroadcastManager.getInstance(SimImportService.this).sendBroadcast(result);

            sPending.remove(this);

            // Only notify of completion if all the import requests have finished. We're using
            // the same notification for imports so in the rare case that a user has started
            // multiple imports the notification won't go away until all of them complete.
            if (sPending.isEmpty()) {
                stopForeground(false);
                mNotificationManager.notify(NOTIFICATION_ID, notification);
            }
            notifyStateChanged();
        }
    }
}
Loading