DO NOT MERGE Add notification for SIM import
This provides feedback to the user if the import takes some time. Also
moved SIM import into it's own service instead of ContactSaveService
to prevent blocking the save service with a long-running operation.
Test
manually verified that notification is displayed when contacts are
imported from the SIM card
Bug 32781237
Change-Id: I8f26e524a08b62f69ff06ddb45cec2db5e98fe24
(cherry picked from commit ba47b41205ddcc3872d52bede1f6aaffb4c874b8)
diff --git a/src/com/android/contacts/ContactSaveService.java b/src/com/android/contacts/ContactSaveService.java
index 6c44a42..76a77c0 100755
--- a/src/com/android/contacts/ContactSaveService.java
+++ b/src/com/android/contacts/ContactSaveService.java
@@ -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.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.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.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.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 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 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 @@
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);
}
@@ -1752,58 +1740,6 @@
}
/**
- * 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.
*
* This exists purely for debugging and manual testing. Since this service uses a single thread
diff --git a/src/com/android/contacts/SimImportFragment.java b/src/com/android/contacts/SimImportFragment.java
index b512599..dc4cabf 100644
--- a/src/com/android/contacts/SimImportFragment.java
+++ b/src/com/android/contacts/SimImportFragment.java
@@ -281,10 +281,8 @@
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) {
diff --git a/src/com/android/contacts/SimImportService.java b/src/com/android/contacts/SimImportService.java
new file mode 100644
index 0000000..7a4997e
--- /dev/null
+++ b/src/com/android/contacts/SimImportService.java
@@ -0,0 +1,313 @@
+/*
+ * 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.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";
+
+ 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<>();
+
+ /**
+ * Returns whether an import for sim has been requested
+ *
+ * <p>This should be called from the UI thread</p>
+ */
+ public static boolean isImporting(SimCard sim) {
+ for (ImportTask task : sPending) {
+ if (task.getSim().equals(sim)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns whether there is any imports still pending
+ *
+ * <p>This should be called from the UI thread</p>
+ */
+ public static boolean isRunning() {
+ return !sPending.isEmpty();
+ }
+
+ /**
+ * 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();
+ }
+ }
+}
diff --git a/src/com/android/contacts/common/preference/DisplayOptionsPreferenceFragment.java b/src/com/android/contacts/common/preference/DisplayOptionsPreferenceFragment.java
index e2782f8..08846a8 100644
--- a/src/com/android/contacts/common/preference/DisplayOptionsPreferenceFragment.java
+++ b/src/com/android/contacts/common/preference/DisplayOptionsPreferenceFragment.java
@@ -43,8 +43,8 @@
import android.view.ViewGroup;
import android.widget.FrameLayout;
-import com.android.contacts.ContactSaveService;
import com.android.contacts.R;
+import com.android.contacts.SimImportService;
import com.android.contacts.common.ContactsUtils;
import com.android.contacts.common.compat.TelecomManagerUtil;
import com.android.contacts.common.compat.TelephonyManagerCompat;
@@ -192,7 +192,7 @@
mSaveServiceListener = new SaveServiceResultListener();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
mSaveServiceListener,
- new IntentFilter(ContactSaveService.BROADCAST_SIM_IMPORT_COMPLETE));
+ new IntentFilter(SimImportService.BROADCAST_SIM_IMPORT_COMPLETE));
}
@Override
@@ -401,20 +401,20 @@
public void onReceive(Context context, Intent intent) {
final long now = System.currentTimeMillis();
final long opStart = intent.getLongExtra(
- ContactSaveService.EXTRA_OPERATION_REQUESTED_AT_TIME, now);
+ SimImportService.EXTRA_OPERATION_REQUESTED_AT_TIME, now);
// If it's been over 30 seconds the user is likely in a different context so suppress
// the toast message.
if (now - opStart > 30*1000) return;
- final int code = intent.getIntExtra(ContactSaveService.EXTRA_RESULT_CODE,
- ContactSaveService.RESULT_UNKNOWN);
- final int count = intent.getIntExtra(ContactSaveService.EXTRA_RESULT_COUNT, -1);
- if (code == ContactSaveService.RESULT_SUCCESS && count > 0) {
+ final int code = intent.getIntExtra(SimImportService.EXTRA_RESULT_CODE,
+ SimImportService.RESULT_UNKNOWN);
+ final int count = intent.getIntExtra(SimImportService.EXTRA_RESULT_COUNT, -1);
+ if (code == SimImportService.RESULT_SUCCESS && count > 0) {
Snackbar.make(mRootView, getResources().getQuantityString(
R.plurals.sim_import_success_toast_fmt, count, count),
Snackbar.LENGTH_LONG).show();
- } else if (code == ContactSaveService.RESULT_FAILURE) {
+ } else if (code == SimImportService.RESULT_FAILURE) {
Snackbar.make(mRootView, R.string.sim_import_failed_toast,
Snackbar.LENGTH_LONG).show();
}