【问题标题】:Import contacts from phone to list in my app in android [duplicate]将联系人从手机导入到我在 android 的应用程序中的列表 [重复]
【发布时间】:2015-12-17 11:52:10
【问题描述】:

在我的应用中,我想让用户显示他们手机中的联系人。我用这个example 从应用程序中打开我的手机通讯录。但是现在我想通过复制手机中的所有联系人来在我的应用程序中列出联系人列表。最好的方法是什么?

编辑:

我已经知道如何显示联系人,但我不知道如何将它们保存到 sqlite db。我是一个初学者,所以任何帮助表示赞赏。

【问题讨论】:

    标签: java android android-contacts


    【解决方案1】:

    试试这个对我有用的例子。

    首先,您需要在 mainifest 文件中设置权限。您的 Mainifest 文件应如下所示。

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalzer.listviewcontacts"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="15" />
    
    <uses-permission 
        android:name="android.permission.READ_CONTACTS" />
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    

    完成此操作后,您需要在布局文件夹中创建两个 XML 文件。

    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <ListView
        android:id="@+id/lst_contacts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />
    
    </RelativeLayout>
    

    lv_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    

    <TextView 
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"        
        android:textSize="20dp"   
        android:textStyle="bold" />
    
    <ImageView 
        android:id="@+id/iv_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_name"
        android:layout_centerHorizontal="true"
        android:padding="5dp" />
    
    <TextView 
        android:id="@+id/tv_details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/iv_photo"        
          />
    
    </RelativeLayout>
    

    创建布局文件后,您的 MainActivity 类将如下所示。

    MainActivity.Java

    public class MainActivity extends Activity {
    
    SimpleCursorAdapter mAdapter;
    MatrixCursor mMatrixCursor;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // The contacts from the contacts content provider is stored in this
        // cursor
        mMatrixCursor = new MatrixCursor(new String[] { "_id", "name", "photo",
                "details" });
    
        // Adapter to set data in the listview
        mAdapter = new SimpleCursorAdapter(getBaseContext(),
                R.layout.lv_layout, null, new String[] { "name", "photo",
                        "details" }, new int[] { R.id.tv_name, R.id.iv_photo,
                        R.id.tv_details }, 0);
    
        // Getting reference to listview
        ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
    
        // Setting the adapter to listview
        lstContacts.setAdapter(mAdapter);
    
        // Creating an AsyncTask object to retrieve and load listview with
        // contacts
        ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
    
        // Starting the AsyncTask process to retrieve and load listview with
        // contacts
        listViewContactsLoader.execute();
    
    }
    
    /** An AsyncTask class to retrieve and load listview with contacts */
    private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
    
        @Override
        protected Cursor doInBackground(Void... params) {
            Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
    
            // Querying the table ContactsContract.Contacts to retrieve all the
            // contacts
            Cursor contactsCursor = getContentResolver().query(contactsUri,
                    null, null, null,
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
    
            if (contactsCursor.moveToFirst()) {
                do {
                    long contactId = contactsCursor.getLong(contactsCursor
                            .getColumnIndex("_ID"));
    
                    Uri dataUri = ContactsContract.Data.CONTENT_URI;
    
                    // Querying the table ContactsContract.Data to retrieve
                    // individual items like
                    // home phone, mobile phone, work email etc corresponding to
                    // each contact
                    Cursor dataCursor = getContentResolver().query(dataUri,
                            null,
                            ContactsContract.Data.CONTACT_ID + "=" + contactId,
                            null, null);
    
                    String displayName = "";
                    String nickName = "";
                    String homePhone = "";
                    String mobilePhone = "";
                    String workPhone = "";
                    String photoPath = "" + R.drawable.blank;
                    byte[] photoByte = null;
                    String homeEmail = "";
                    String workEmail = "";
                    String companyName = "";
                    String title = "";
    
                    if (dataCursor.moveToFirst()) {
                        // Getting Display Name
                        displayName = dataCursor
                                .getString(dataCursor
                                        .getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                        do {
    
                            // Getting NickName
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                                nickName = dataCursor.getString(dataCursor
                                        .getColumnIndex("data1"));
    
                            // Getting Phone numbers
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
                                switch (dataCursor.getInt(dataCursor
                                        .getColumnIndex("data2"))) {
                                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                    homePhone = dataCursor.getString(dataCursor
                                            .getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                    mobilePhone = dataCursor
                                            .getString(dataCursor
                                                    .getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                    workPhone = dataCursor.getString(dataCursor
                                            .getColumnIndex("data1"));
                                    break;
                                }
                            }
    
                            // Getting EMails
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
                                switch (dataCursor.getInt(dataCursor
                                        .getColumnIndex("data2"))) {
                                case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
                                    homeEmail = dataCursor.getString(dataCursor
                                            .getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
                                    workEmail = dataCursor.getString(dataCursor
                                            .getColumnIndex("data1"));
                                    break;
                                }
                            }
    
                            // Getting Organization details
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)) {
                                companyName = dataCursor.getString(dataCursor
                                        .getColumnIndex("data1"));
                                title = dataCursor.getString(dataCursor
                                        .getColumnIndex("data4"));
                            }
    
                            // Getting Photo
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)) {
                                photoByte = dataCursor.getBlob(dataCursor
                                        .getColumnIndex("data15"));
    
                                if (photoByte != null) {
                                    Bitmap bitmap = BitmapFactory
                                            .decodeByteArray(photoByte, 0,
                                                    photoByte.length);
    
                                    // Getting Caching directory
                                    File cacheDirectory = getBaseContext()
                                            .getCacheDir();
    
                                    // Temporary file to store the contact image
                                    File tmpFile = new File(
                                            cacheDirectory.getPath() + "/wpta_"
                                                    + contactId + ".png");
    
                                    // The FileOutputStream to the temporary
                                    // file
                                    try {
                                        FileOutputStream fOutStream = new FileOutputStream(
                                                tmpFile);
    
                                        // Writing the bitmap to the temporary
                                        // file as png file
                                        bitmap.compress(
                                                Bitmap.CompressFormat.PNG, 100,
                                                fOutStream);
    
                                        // Flush the FileOutputStream
                                        fOutStream.flush();
    
                                        // Close the FileOutputStream
                                        fOutStream.close();
    
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
    
                                    photoPath = tmpFile.getPath();
                                }
    
                            }
    
                        } while (dataCursor.moveToNext());
    
                        String details = "";
    
                        // Concatenating various information to single string
                        if (homePhone != null && !homePhone.equals(""))
                            details = "HomePhone : " + homePhone + "\n";
                        if (mobilePhone != null && !mobilePhone.equals(""))
                            details += "MobilePhone : " + mobilePhone + "\n";
                        if (workPhone != null && !workPhone.equals(""))
                            details += "WorkPhone : " + workPhone + "\n";
                        if (nickName != null && !nickName.equals(""))
                            details += "NickName : " + nickName + "\n";
                        if (homeEmail != null && !homeEmail.equals(""))
                            details += "HomeEmail : " + homeEmail + "\n";
                        if (workEmail != null && !workEmail.equals(""))
                            details += "WorkEmail : " + workEmail + "\n";
                        if (companyName != null && !companyName.equals(""))
                            details += "CompanyName : " + companyName + "\n";
                        if (title != null && !title.equals(""))
                            details += "Title : " + title + "\n";
    
                        // Adding id, display name, path to photo and other
                        // details to cursor
                        mMatrixCursor.addRow(new Object[] {
                                Long.toString(contactId), displayName,
                                photoPath, details });
                    }
    
                } while (contactsCursor.moveToNext());
            }
            return mMatrixCursor;
        }
    
        @Override
        protected void onPostExecute(Cursor result) {
            // Setting the cursor containing contacts to listview
            mAdapter.swapCursor(result);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    }
    

    【讨论】:

    • 谢谢 Umer,这对我有用。它会打开一个包含我所有联系人的漂亮列表。虽然打开列表有点慢。关于加快速度的任何建议:)
    • @Kemo 随时欢迎您。是的,这段代码有很多性能改进,我只是很快将其发​​送给您,以便解决您的问题 :) 我会尽快为您提供优化的代码以快速处理它:)
    【解决方案2】:

    你可以这样做:

    添加功能:

    private List<Person> getContactList(){
            ArrayList<Person> contactList = new ArrayList<Person>();
    
            Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
            String[] PROJECTION = new String[] {
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER,
            };
            String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
            Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
    
    
            if (contacts.getCount() > 0)
            {
                while(contacts.moveToNext()) {
                    Person aContact = new Person();
                    int idFieldColumnIndex = 0;
                    int nameFieldColumnIndex = 0;
                    int numberFieldColumnIndex = 0;
    
                    String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
    
                    nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
                    if (nameFieldColumnIndex > -1)
                    {
                        aContact.setName(contacts.getString(nameFieldColumnIndex));
                    }
    
                    PROJECTION = new String[] {Phone.NUMBER};
                    final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
                    if(phone.moveToFirst()) {
                        while(!phone.isAfterLast())
                        {
                            numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
                            if (numberFieldColumnIndex > -1)
                            {
                                aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
                                phone.moveToNext();
                                TelephonyManager mTelephonyMgr;
                                mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                                if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
                                {
                                    contactList.add(aContact);  
                                }
                            }
                        }
                    }
                    phone.close();
                }
    
                contacts.close();
            }
    
            return contactList;
        }
    

    Person.java

    public class Person {
        String myName = "";
        String myNumber = "";
    
        public String getName() {
            return myName;
        }
    
        public void setName(String name) {
            myName = name;
        }
    
        public String getPhoneNum() {
            return myNumber;
        }
    
        public void setPhoneNum(String number) {
            myNumber = number;
        }
    }
    

    希望这会对你有所帮助。

    【讨论】:

    • 非常感谢您的回复,我刚刚尝试了 Umer 的解决方案,它成功了。我也会试试这个,它看起来更紧凑。再次感谢
    • @Kemo,非常欢迎。 :)
    猜你喜欢
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    相关资源
    最近更新 更多