summaryrefslogtreecommitdiffstats
path: root/src/com/android/contacts/incall/InCallMetricsHelper.java
blob: b22214114b36c1a8127b0f982ab5b3d6bda7c76b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/*
 * Copyright (C) 2016 The CyanogenMod 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.incall;

import android.app.AlarmManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import android.os.Handler;
import android.os.HandlerThread;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;

import com.android.phone.common.ambient.AmbientConnection;
import com.android.phone.common.incall.CallMethodInfo;
import com.android.phone.common.incall.ContactsDataSubscription;
import com.cyanogen.ambient.analytics.AnalyticsServices;
import com.cyanogen.ambient.analytics.Event;
import com.cyanogen.ambient.common.CyanogenAmbientUtil;
import com.cyanogen.ambient.incall.InCallServices;
import com.google.common.base.Joiner;
import cyanogenmod.providers.CMSettings;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

public class InCallMetricsHelper {
    private static final String TAG = InCallMetricsHelper.class.getSimpleName();

    private static final boolean DEBUG = false;
    private static final String CATEGORY_PREFIX = "contacts.incall.";

    public static final String NUDGE_ID_INVALID = "-1";
    public static final int EVENT_DISMISS = 0;
    public static final int EVENT_ACCEPT = 1;

    private static InCallMetricsHelper sInstance;
    private InCallMetricsDbHelper mDbHelper;
    private static final String HANDLER_THREAD_NAME = "InCallMetricsHandler";
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private Context mContext;
    private int mAmbientStatus = CyanogenAmbientUtil.MISSING;
    private static final int SCHEDULER_JOB_ID = 1;

    public enum Categories {
        USER_ACTIONS("USER_ACTIONS"),
        INAPP_NUDGES("INAPP_NUDGES"),
        UNKNOWN("UNKNOWN");

        private String mValue;
        Categories(String s) {
            mValue = s;
        }
        public String value() {
            return mValue;
        }
    }

    public enum Events {
        CONTACTS_MANUAL_MERGED("CONTACTS_MANUAL_MERGED"),
        CONTACTS_AUTO_MERGED("CONTACTS_AUTO_MERGED"),
        INVITES_SENT("INVITES_SENT"),
        DIRECTORY_SEARCH("DIRECTORY_SEARCH"),
        INAPP_NUDGE_CONTACTS_LOGIN("INAPP_NUDGE_CONTACTS_LOGIN"),
        INAPP_NUDGE_CONTACTS_INSTALL("INAPP_NUDGE_CONTACTS_INSTALL"),
        INAPP_NUDGE_CONTACTS_TAB_LOGIN("INAPP_NUDGE_CONTACTS_TAB_LOGIN"),
        UNKNOWN("UNKNOWN");

        private String mValue;
        Events(String s) {
            mValue = s;
        }
        public String value() {
            return mValue;
        }
    }

    public enum Parameters {
        ACTION_LOCATION("ACTION_LOCATION"),
        CATEGORY("CATEGORY"),
        COUNT("COUNT"),
        EVENT_ACCEPTANCE("EVENT_ACCEPTANCE"),
        EVENT_ACCEPTANCE_TIME("EVENT_ACCEPTANCE_TIME"),
        EVENT_NAME("EVENT_NAME"),
        NUDGE_ID("NUDGE_ID"),
        PROVIDER_NAME("PROVIDER_NAME");

        private String mValue;

        Parameters(String s) {
            mValue = s;
        }

        public String value() {
            return mValue;
        }

        public String toCol() {
            return mValue.toLowerCase();
        }
   }
    private static Comparator<String> sRawIdComparator = new Comparator<String> () {
        @Override
        public int compare(String o1, String o2)  {
            return Integer.parseInt(o1) - Integer.parseInt(o2);
        }
    };

    public static void init(Context context) {
        InCallMetricsHelper helper = getInstance(context);
        helper.mAmbientStatus = CyanogenAmbientUtil.isCyanogenAmbientAvailable(context);
        // only set job schedule flag default to true if there is Ambient
        boolean scheduleJob = (helper.mAmbientStatus == CyanogenAmbientUtil.SUCCESS);
        JobScheduler jobScheduler =
                (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        if (jobScheduler == null) {
            Log.e(TAG, "JOB_SCHEDULER_SERVICE error, cannot schedule metrics collection.");
            return;
        }
        // check for outstanding job
        for (JobInfo jobInfo : jobScheduler.getAllPendingJobs()) {
            if (jobInfo.getId() == SCHEDULER_JOB_ID) {
                if (helper.mAmbientStatus != CyanogenAmbientUtil.SUCCESS) {
                    // cancel job if Ambient is not available
                    jobScheduler.cancel(SCHEDULER_JOB_ID);
                }
                // there's already pending job scheduled, no need to schedule a new one
                scheduleJob = false;
                if (DEBUG) {
                    Log.d(TAG, "init, Job already scheduled");
                }
                break;
            }
        }
        if (scheduleJob) {
            if (DEBUG) {
                Log.d(TAG, "init, schedule new Job");
            }
            JobInfo.Builder jobBuilder = new JobInfo.Builder(SCHEDULER_JOB_ID,
                    new ComponentName(context, InCallMetricsJobService.class));
            jobBuilder.setPeriodic(AlarmManager.INTERVAL_HALF_HOUR)
                    .setPersisted(true)
                    .setBackoffCriteria(AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                            JobInfo.BACKOFF_POLICY_EXPONENTIAL);
            jobScheduler.schedule(jobBuilder.build());
        }
    }

    public static synchronized InCallMetricsHelper getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new InCallMetricsHelper();
            sInstance.mContext = context;
            // init handler
            sInstance.mHandlerThread = new HandlerThread(HANDLER_THREAD_NAME);
            sInstance.mHandlerThread.start();
            sInstance.mHandler = new Handler(sInstance.mHandlerThread.getLooper());
            sInstance.mDbHelper = InCallMetricsDbHelper.getInstance(context);
        }
        return sInstance;
    }

    /**
     * Gather all metrics entries from tables and send to Ambient.
     *
     * @param  context  context to be used in db
     * @return the posted Runnable
     */
    public static Runnable prepareAndSend(final Context context, final InCallMetricsJobService
            .JobDoneCallback jobDoneCallback, final JobParameters params) {
        InCallMetricsHelper helper = getInstance(context);
        Runnable sendTask = new Runnable() {
            @Override
            public void run() {
                if (!statsOptIn(context)) {
                    if (jobDoneCallback != null) {
                        jobDoneCallback.callback(params, false);
                    }
                    return;
                }

                InCallMetricsHelper helper = getInstance(context);
                // In App events
                List<ContentValues> allList =
                        helper.mDbHelper.getAllEntries(Categories.INAPP_NUDGES, true);
                // User Actions events
                allList.addAll(helper.mDbHelper.getAllEntries(Categories.USER_ACTIONS, true));
                for (ContentValues cv : allList) {
                    Categories cat = cv.containsKey(Parameters.CATEGORY.toCol()) ?
                            Categories.valueOf(cv.getAsString(Parameters.CATEGORY.toCol())) :
                            Categories.UNKNOWN;
                    Events event = cv.containsKey(Parameters.EVENT_NAME.toCol()) ?
                            Events.valueOf(cv.getAsString(Parameters.EVENT_NAME.toCol())) :
                            Events.UNKNOWN;
                    Set<String> plugins = ContactsDataSubscription.get(context)
                            .getAllPluginComponentNames();
                    sendEvent(context, cat, event, getExtraFields(cat, event, cv), plugins);

                }
                if (jobDoneCallback != null) {
                    jobDoneCallback.callback(params, false);
                }
            }
        };
        helper.mHandler.post(sendTask);
        return sendTask;
    }

    /**
     * Map ContentValues pair from db to <Parameters, value> pairs
     *
     * @param  event    metric event
     * @param  cat      metric category
     * @param  cv
     */
    private static HashMap<Parameters, Object> getExtraFields(Categories cat, Events event,
            ContentValues cv) {
        HashMap<Parameters, Object> map = new HashMap<Parameters, Object>();
        map.put(Parameters.PROVIDER_NAME, cv.getAsString(Parameters.PROVIDER_NAME.toCol()));
        switch (cat) {
            case INAPP_NUDGES:
                switch (event) {
                    case INAPP_NUDGE_CONTACTS_LOGIN:
                    case INAPP_NUDGE_CONTACTS_INSTALL:
                    case INAPP_NUDGE_CONTACTS_TAB_LOGIN:
                        map.put(Parameters.COUNT, cv.getAsInteger(Parameters.COUNT.toCol()));
                        map.put(Parameters.NUDGE_ID, cv.getAsString(Parameters.NUDGE_ID.toCol()));
                        map.put(Parameters.EVENT_ACCEPTANCE_TIME,
                                cv.getAsLong(Parameters.EVENT_ACCEPTANCE_TIME.toCol()));
                        map.put(Parameters.EVENT_ACCEPTANCE,
                                cv.getAsInteger(Parameters.EVENT_ACCEPTANCE.toCol()) == 0 ?
                                        Boolean.FALSE : Boolean.TRUE);
                        break;
                    default:
                        break;
                }
                break;
            case USER_ACTIONS:
                switch (event) {
                    case CONTACTS_AUTO_MERGED:
                    case CONTACTS_MANUAL_MERGED:
                    case INVITES_SENT:
                    case DIRECTORY_SEARCH:
                        map.put(Parameters.COUNT, cv.getAsInteger(Parameters.COUNT.toCol()));
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
        if (DEBUG) {
            Log.d(TAG, event.value() + ": " + map.toString());
        }
        return map;
    }

    /**
     * Send AnalyticsService events to Ambient and InCall plugins
     *
     * @param  context      context
     * @param  cat          metric category
     * @param  eventName    metric event name
     * @param  extraFields  <Parameter, Object> pairs to be included in Ambient Event
     * @param  pluginSet    a set of available plugin component names for sending lookup
     */
    private static void sendEvent(Context context, Categories cat, Events eventName,
            HashMap<Parameters, Object> extraFields, Set<String> pluginSet) {
        Event.Builder eventBuilder = new Event.Builder(CATEGORY_PREFIX + cat.value(), eventName
                .value());
        if (extraFields != null && extraFields.size() > 0) {
            for (Parameters param : extraFields.keySet()) {
                eventBuilder.addField(param.value(), String.valueOf(extraFields.get(param)));
            }
        }
        Event event = eventBuilder.build();
        if (DEBUG) Log.d(TAG, event.toString());
        // send to Ambient
        AnalyticsServices.AnalyticsApi.sendEvent(AmbientConnection.CLIENT.get(context), event);
        // send to selective plugin
        String providers = extraFields.containsKey(Parameters.PROVIDER_NAME) ?
                (String) extraFields.get(Parameters.PROVIDER_NAME) : "";
        sendEventToProviders(context, cat, eventName, event, providers, pluginSet);
    }

    /**
     * Send Ambient Events to InCall providers, if they exist in the set of currently available
     * InCall plugins
     *
     * @param  context      context
     * @param  cat          metric category
     * @param  eventName    metric event name
     * @param  pluginSet    a set of available plugin component names for sending lookup
     */
    private static void sendEventToProviders(Context context, Categories cat, Events eventName,
            Event event, String providers, Set<String> pluginSet) {
        if (!isWhiteListed(cat, eventName)) {
            return;
        }
        if (DEBUG) Log.d(TAG, "sendEventToProviders:" + providers);
        String[] providerList = providers.split(",");
        for (String provider : providerList) {
            if (pluginSet.contains(provider)) {
                if (DEBUG) Log.d(TAG, "sendEventToProvider:" + provider);
                InCallServices.getInstance().sendAnalyticsEventToPlugin(
                        AmbientConnection.CLIENT.get(context),
                        ComponentName.unflattenFromString(provider), event);
            }
        }
    }

    /**
     * Check if the category/event are whitelisted to be able to sent to InCall providers
     *
     * @param  cat          metric category
     * @param  eventName    metric event name
     */
    private static boolean isWhiteListed(Categories cat, Events eventName) {
        return true;
    }

    public static void increaseCount(final Context context, final Events event, final String
            provider) {
        final InCallMetricsHelper helper = getInstance(context);
        helper.mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!statsOptIn(context)) {
                    return;
                }
                helper.mDbHelper.incrementUserActionsParam(provider, "", event.value(),
                        Categories.USER_ACTIONS.value(),
                        Parameters.COUNT.value().toLowerCase());
            }
        });
    }

    /**
     * Set a specific parameter to a certain value
     *
     * @param  context      context
     * @param  component    InCall provider component name
     * @param  cat          metric category
     * @param  event        metric event name
     * @param  param        metric parameter to set
     * @param  value        metric parameter value to set to
     * @param  nudgeId      nudge ID corresponding to the
     */
    public static void setValue(final Context context, final ComponentName component,
            final Categories cat, final Events event, final Parameters param,
            final Object value, final String nudgeId) {
        final InCallMetricsHelper helper = getInstance(context);
        helper.mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!statsOptIn(context)) {
                    return;
                }
                switch (cat) {
                    case INAPP_NUDGES:
                        switch (param) {
                            case EVENT_ACCEPTANCE:
                                helper.mDbHelper.setInAppAcceptance(component.flattenToString(),
                                        event.value(), cat.value(), (Integer) value, nudgeId);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * Increases the impression count for different nudges in
     *
     * @param  context  context
     * @param  cmi      CallMethodInfo for the entry
     * @pram   even     Events type
     */
    public static void increaseImpressionCount(final Context context, final CallMethodInfo cmi,
            final Events event) {
        if (cmi == null || cmi.mComponent == null) {
            return;
        }
        final InCallMetricsHelper helper = getInstance(context);
        helper.mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!statsOptIn(context)) {
                    return;
                }
                switch (event) {
                    case INAPP_NUDGE_CONTACTS_INSTALL:
                        helper.mDbHelper.incrementInAppParam(cmi.mComponent.flattenToString(),
                                event.value(), Categories.INAPP_NUDGES.value(),
                                generateNudgeId(cmi.mInstallNudgeSubtitle),
                                Parameters.COUNT.toCol());
                        break;
                    case INAPP_NUDGE_CONTACTS_LOGIN:
                        helper.mDbHelper.incrementInAppParam(cmi.mComponent.flattenToString(),
                                event.value(), Categories.INAPP_NUDGES.value(),
                                generateNudgeId(cmi.mLoginNudgeSubtitle),
                                Parameters.COUNT.toCol());
                        break;
                    case INAPP_NUDGE_CONTACTS_TAB_LOGIN:
                        if (!cmi.mIsAuthenticated) {
                            helper.mDbHelper.incrementInAppParam(cmi.mComponent.flattenToString(),
                                    event.value(),
                                    Categories.INAPP_NUDGES.value(),
                                    generateNudgeId(cmi.mLoginSubtitle),
                                    Parameters.COUNT.toCol());
                        }
                    default:
                        break;
                }
            }
        });
    }

    /**
     * Increases manual contact merge counts
     *
     * @param  context          context
     * @param  contactIdForJoin the primary contact ID to be merged
     * @param  contactId        the secondary contact ID to be merged
     */
    public static void increaseContactManualMergeCount(final Context context,
            final long contactIdForJoin, final long contactId) {
        final InCallMetricsHelper helper = getInstance(context);
        helper.mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!statsOptIn(context)) {
                    return;
                }
                SortedSet<String> rawIdSet = new TreeSet<String>(sRawIdComparator);
                SortedSet<String> providerSet = queryContactProviderByContactIds(context,
                        contactIdForJoin, contactId, rawIdSet);
                String[] rawIdArray = rawIdSet.toArray(new String[rawIdSet.size()]);
                List<String> providerList = new ArrayList<String>(providerSet);
                String joinedProvider = providerList.size() == 0 ? "" :
                        Joiner.on(",").skipNulls().join(providerList);
                String joinedRawIds = rawIdArray.length == 0 ? "" :
                        Joiner.on(",").skipNulls().join(rawIdArray);
                helper.mDbHelper.incrementUserActionsParam(joinedProvider, joinedRawIds,
                        InCallMetricsHelper.Events.CONTACTS_MANUAL_MERGED.value(),
                        Categories.USER_ACTIONS.value(), Parameters.COUNT.toCol());
            }
        });
    }

    /**
     * Increases auto contact merge counts
     *
     * @param  context  context
     * @param  rawIds   the merged raw contact IDs
     */
    public static void increaseContactAutoMergeCount(final Context context, final String rawIds) {
        final InCallMetricsHelper helper = getInstance(context);
        if (helper.mAmbientStatus != CyanogenAmbientUtil.SUCCESS) {
            return;
        }
        helper.mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!statsOptIn(context)) {
                    return;
                }
                String[] rawIdArray = rawIds.split(",");
                Arrays.sort(rawIdArray, sRawIdComparator);
                SortedSet<String> providerSet = queryContactProviderByRawContactIds(context,
                        rawIdArray);
                List<String> providerList = new ArrayList<String>(providerSet);

                String joinedProvider = providerList.size() == 0 ? "" :
                        Joiner.on(",").skipNulls().join(providerList);
                String joinedRawIds = rawIdArray.length == 0 ? "" :
                        Joiner.on(",").skipNulls().join(rawIdArray);
                helper.mDbHelper.incrementUserActionsParam(joinedProvider,
                        joinedRawIds,
                        InCallMetricsHelper.Events.CONTACTS_AUTO_MERGED.value(),
                        Categories.USER_ACTIONS.value(), Parameters.COUNT.toCol());
            }
        });

    }

    /**
     * Check if the provided contact IDs is from an account type that matches a InCall provider.
     *
     * @param  context     context
     * @param  contactId   the primary contact ID to be merged
     * @param  contactId2  the secondary contact ID to be merged
     * @param  rawIdSet    merged raw contac ID set filled by this method
     */
    private static SortedSet<String> queryContactProviderByContactIds(Context context, long
            contactId, long contactId2, Set<String> rawIdSet) {
        SortedSet<String> providerSet = new TreeSet<String>();
        HashMap<String, String> pluginMap = InCallPluginUtils.getPluginAccountComponentPairs
                (context);
        try (Cursor cursor = context.getContentResolver().query(RawContacts.CONTENT_URI,
                    new String[]{RawContacts.ACCOUNT_TYPE, RawContacts._ID},
                    RawContacts.CONTACT_ID + "=? OR " + RawContacts.CONTACT_ID + "=?",
                    new String[]{String.valueOf(contactId), String.valueOf(contactId2)}, null)) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String accountType = cursor.getString(0); // RawContacts.ACCOUNT_TYPE
                    if (pluginMap.containsKey(accountType)) {
                        // a plugin, use component name
                        providerSet.add(pluginMap.get(accountType));
                    } else {
                        // not a plugin, use account type instead
                        providerSet.add(accountType);
                    }
                    rawIdSet.add(String.valueOf(cursor.getInt(1))); // _ID
                    if (DEBUG) Log.d(TAG, "queryContactProvider:" + cursor.getString(0));
                }
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "queryContactProiderByContactIds exception: ", e);
        }
        return providerSet;
    }

    /**
     * Check if the provided raw contact IDs is from an account type that matches an InCall
     * provider.
     *
     * @param  context  context
     * @param  rawIds   raw contact IDs of the contacts
     */
    private static SortedSet<String> queryContactProviderByRawContactIds(Context context, String[]
            rawIds) {
        SortedSet<String> providerSet = new TreeSet<String>();
        HashMap<String, String> pluginMap = InCallPluginUtils.getPluginAccountComponentPairs
                (context);
        for (String rawId : rawIds) {
            try (Cursor cursor = context.getContentResolver().query(RawContacts.CONTENT_URI,
                        new String[]{RawContacts.ACCOUNT_TYPE},
                        RawContacts._ID + "=?",
                        new String[]{rawId}, null)) {
                if (cursor != null) {
                    while (cursor.moveToFirst()) {
                        String accountType = cursor.getString(0); // RawContacts.ACCOUNT_TYPE
                        if (pluginMap.containsKey(accountType)) {
                            providerSet.add(pluginMap.get(accountType));
                        } else {
                            providerSet.add(accountType);
                        }
                        providerSet.add(accountType);
                        if (DEBUG) Log.d(TAG, "queryContactProvider:" + accountType);
                    }
                }
            } catch (RuntimeException e) {
                Log.e(TAG, "queryContactProviderByRawContactIds exception: ", e);
            }
        }
        return providerSet;
    }

    public static String generateNudgeId(String data) {
        if (TextUtils.isEmpty(data)) {
            return "";
        }
        return java.util.UUID.nameUUIDFromBytes(data.getBytes()).toString();
    }

    private static boolean statsOptIn(Context context) {
        return CMSettings.Secure.getInt(context.getContentResolver(),
                CMSettings.Secure.STATS_COLLECTION, 1) == 1;
    }

    public static void stopTask(Context context, Runnable task) {
        final InCallMetricsHelper helper = getInstance(context);
        helper.mHandler.removeCallbacks(task);
    }
}