从android中的电话簿中检索whatsapp联系人

Posted

技术标签:

【中文标题】从android中的电话簿中检索whatsapp联系人【英文标题】:Retrieve whatsapp contacts from phonebook in android 【发布时间】:2014-05-27 08:30:49 【问题描述】:

当我在手机中查看我的联系人时,我也会看到那些拥有 whatsapp 帐户的人的 whatsapp 号码。我想要做的是过滤我的联系人列表并显示与 whatsapp 同步的号码。我已成功检索所有与它关联但不显示whatsappaccount的联系人ID,号码和帐户。仅显示关联的google帐户。有没有办法从本地电话簿本身获取whatsapp联系人?我使用了以下代码:

ContentResolver cr1 = getContentResolver();
Cursor cur = cr1.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cur.getCount() > 0) 
    
        while (cur.moveToNext()) 
        
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) 
            
                Cursor pCur = cr1.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]  id , null);
                while (pCur.moveToNext()) 
                
                    //phoneContactList.add(name);
                    Log.i("Contact List", name);
                    Log.i("Contact List", id);
                    
                    getContactAccount(id,cr1);
                
                pCur.close();
            
        
    


public void getContactAccount(String id,ContentResolver contentResolver)
        Cursor cursor = null;
        try 
             cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
                     new String[]ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE,
                     ContactsContract.RawContacts.CONTACT_ID +"=?",
                     new String[]String.valueOf(id),
                     null);
             
            if (cursor != null && cursor.getCount() >0)
                cursor.moveToFirst();
                System.out.println("Account name is"+cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
                System.out.println("Account type is"+cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
                cursor.close();
            
         catch (Exception e) 
            System.out.println(""+this.getClass().getName()+","+ e.getMessage());
         finally
          cursor.close();
        
    

【问题讨论】:

试试这个***.com/questions/35448250/…它只读联系人谁在whatsapp帐户... 【参考方案1】:

使用以下代码从电话簿中获取具有相关 WhatsApp 号码的 WhatsApp 联系人:

private void displayWhatsAppContacts() 

    final String[] projection = 
            ContactsContract.Data.CONTACT_ID,
            ContactsContract.Data.DISPLAY_NAME,
            ContactsContract.Data.MIMETYPE,
            "account_type",
            ContactsContract.Data.DATA3,
    ;

    final String selection = ContactsContract.Data.MIMETYPE + " =? and account_type=?";
    final String[] selectionArgs = 
            "vnd.android.cursor.item/vnd.com.whatsapp.profile",
            "com.whatsapp"
    ;

    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(
            ContactsContract.Data.CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null);

    while (c.moveToNext()) 
        String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
        String number = c.getString(c.getColumnIndex(ContactsContract.Data.DATA3));
        String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        Log.v("WhatsApp", "name " +name + " - number - "+number);

    
    Log.v("WhatsApp", "Total WhatsApp Contacts: " + c.getCount());
    c.close();

【讨论】:

如何获取联系人图片? 我必须检查一下,尝试通过调试检查光标中的数据。【参考方案2】:
The MIME type for whatsapp is:  "vnd.android.cursor.item/vnd.com.whatsapp.profile"

使用以下代码:

public class MainActivity extends ActionBarActivity 


    @Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) 
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    


@Override
public boolean onCreateOptionsMenu(Menu menu) 

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) 
        return true;
    
    return super.onOptionsItemSelected(item);


/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment implements LoaderCallbacks<Cursor>,AdapterView.OnItemClickListener 
    /*
     * Defines an array that contains column names to move from
     * the Cursor to the ListView.
     */
 
    private final static String[] FROM_COLUMNS = 
            Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.HONEYCOMB ?
                            Data.DISPLAY_NAME :
                                Data.DISPLAY_NAME
    ;
    /*
     * Defines an array that contains resource ids for the layout views
     * that get the Cursor column contents. The id is pre-defined in
     * the Android framework, so it is prefaced with "android.R.id"
     */
    private final static int[] TO_IDS = 
           android.R.id.text1
    ;
    // Define global mutable variables
    // Define a ListView object
    ListView mContactsList;
    // Define variables for the contact the user selects
    // The contact's _ID value
    long mContactId;
    // The contact's LOOKUP_KEY
    String mContactKey;
    // A content URI for the selected contact
    Uri mContactUri;
 // The column index for the _ID column
    private static final int CONTACT_ID_INDEX = 0;
    // The column index for the LOOKUP_KEY column
    private static final int LOOKUP_KEY_INDEX = 1;
    // Defines the text expression
    private static final String mime_type ="vnd.android.cursor.item/vnd.com.whatsapp.profile";
    private static final String SELECTION =
             Data.MIMETYPE + " = '" + mime_type + "'";
    // Defines a variable for the search string
    private String mSearchString="Gourav";
    // Defines the array to hold values that replace the ?
    private String[] mSelectionArgs =  mSearchString ;
    private static final String[] PROJECTION =
        
            Contacts._ID,
            Contacts.LOOKUP_KEY,
            Data.DISPLAY_NAME,
            Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.HONEYCOMB ?
                            Data.MIMETYPE :
                                Data.MIMETYPE 

        ;
    // An adapter that binds the result Cursor to the ListView
    private SimpleCursorAdapter mCursorAdapter;

    public PlaceholderFragment() 
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        
        return rootView;
    

    @Override
    public void onActivityCreated(Bundle savedInstanceState) 
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
         getLoaderManager().initLoader(0, null, this);
        // Gets the ListView from the View list of the parent activity
        mContactsList = (ListView) getActivity().findViewById(R.id.list);
        // Gets a CursorAdapter
        mCursorAdapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.contact_list,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
    

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) 
        // TODO Auto-generated method stub
          // Get the Cursor
        Cursor cursor = (Cursor) parent.getAdapter().getItem(position);
        // Move to the selected contact
        cursor.moveToPosition(position);
        // Get the _ID value
        mContactId = cursor.getLong(CONTACT_ID_INDEX);
        // Get the selected LOOKUP KEY
        mContactKey = cursor.getString(LOOKUP_KEY_INDEX);
        // Create the contact's content Uri
        mContactUri = Contacts.getLookupUri(mContactId, mContactKey);
        /*
         * You can use mContactUri as the content URI for retrieving
         * the details for a contact.
         */
    

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(
            int arg0, Bundle arg1) 
        // TODO Auto-generated method stub
        /*
         * Makes search string into pattern and
         * stores it in the selection array
         */
        CursorLoader cursor = null;
        mSelectionArgs[0] = "%" + mSearchString + "%";
        Log.d("ON CREATE LOADER", "ONCLREATE LOADER CALLLEd");
        try
        
         cursor=new CursorLoader(
                getActivity(),
                Data.CONTENT_URI,
                PROJECTION,
                SELECTION,
                null,
                null
        );
        
        catch(Exception e)
        
            
            e.printStackTrace();
        
        // Starts the query
        return cursor;
    

    @Override
    public void onLoadFinished(
            android.support.v4.content.Loader<Cursor> arg0, Cursor cursor) 
        // TODO Auto-generated method stub
         Log.d("onLoadFinished", String.valueOf(cursor.getCount()));
           mCursorAdapter.swapCursor(cursor);
    

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> arg0) 
        // TODO Auto-generated method stub
         mCursorAdapter.swapCursor(null);

    





【讨论】:

以上是关于从android中的电话簿中检索whatsapp联系人的主要内容,如果未能解决你的问题,请参考以下文章

从 RawContact Android 读取电话号码

从 Android 中的 URI 检索联系人电话号码

无法从 ListView 项中检索 Intent 的地址和电话号码

从 Android 联系人中检索电话号码在三星上不起作用

安卓。通过电话号码从通讯录中检索名字和姓氏

如何获取联系人/电话号码的“提供者”(skype/whatsapp/google)