PhoneNumberContact.java

 1package eu.siacs.conversations.android;
 2
 3import android.Manifest;
 4import android.content.Context;
 5import android.content.pm.PackageManager;
 6import android.database.Cursor;
 7import android.os.Build;
 8import android.provider.ContactsContract;
 9import android.util.Log;
10
11import java.util.Collections;
12import java.util.HashMap;
13import java.util.Map;
14
15import eu.siacs.conversations.Config;
16import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
17import io.michaelrocks.libphonenumber.android.NumberParseException;
18
19public class PhoneNumberContact extends AbstractPhoneContact {
20
21    private String phoneNumber;
22
23    public String getPhoneNumber() {
24        return phoneNumber;
25    }
26
27    private PhoneNumberContact(Context context, Cursor cursor) throws IllegalArgumentException {
28        super(cursor);
29        try {
30            this.phoneNumber = PhoneNumberUtilWrapper.normalize(context,cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
31        } catch (NumberParseException | NullPointerException e) {
32            throw new IllegalArgumentException(e);
33        }
34    }
35
36    public static Map<String, PhoneNumberContact> load(Context context) {
37        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
38            return Collections.emptyMap();
39        }
40        final String[] PROJECTION = new String[]{ContactsContract.Data._ID,
41                ContactsContract.Data.DISPLAY_NAME,
42                ContactsContract.Data.PHOTO_URI,
43                ContactsContract.Data.LOOKUP_KEY,
44                ContactsContract.CommonDataKinds.Phone.NUMBER};
45        final Cursor cursor;
46        try {
47            cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
48        } catch (Exception e) {
49            return Collections.emptyMap();
50        }
51        final HashMap<String, PhoneNumberContact> contacts = new HashMap<>();
52        while (cursor != null && cursor.moveToNext()) {
53            try {
54                final PhoneNumberContact contact = new PhoneNumberContact(context, cursor);
55                final PhoneNumberContact preexisting = contacts.get(contact.getPhoneNumber());
56                if (preexisting == null || preexisting.rating() < contact.rating()) {
57                    contacts.put(contact.getPhoneNumber(), contact);
58                }
59            } catch (IllegalArgumentException e) {
60                Log.d(Config.LOGTAG, "unable to create phone contact");
61            }
62        }
63        if (cursor != null) {
64            cursor.close();
65        }
66        return contacts;
67    }
68}