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

在android中从电话簿检索whatsapp联系人,android,android-contacts,whatsapp,Android,Android Contacts,Whatsapp,当我在手机中查看我的联系人时,我也看到了那些拥有whatsapp帐户的人的whatsapp号码。我要做的是过滤我的联系人列表并显示与whatsapp同步的号码。我正在成功检索所有联系人id,与之关联的号码和帐户,但不显示whatsapp帐户。只显示关联的google帐户。是否有任何方法从本地电话簿本身获取whatsapp联系人?我使用了以下代码: ContentResolver cr1 = getContentResolver(); Cursor cur = cr1.query(Contacts

当我在手机中查看我的联系人时,我也看到了那些拥有whatsapp帐户的人的whatsapp号码。我要做的是过滤我的联系人列表并显示与whatsapp同步的号码。我正在成功检索所有联系人id,与之关联的号码和帐户,但不显示whatsapp帐户。只显示关联的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();
        }
    }
使用以下代码`:

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);

    }


}

}
公共类MainActivity扩展了ActionBarActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
如果(savedInstanceState==null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container,新的占位符片段()).commit();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
/**
*包含简单视图的占位符片段。
*/
公共静态类PlaceholderFragment扩展片段实现LoaderCallbacks、AdapterView.OnItemClickListener{
/*
*定义包含要从中移动的列名的数组
*将光标移动到ListView。
*/
_列中的私有最终静态字符串[]={
Build.VERSION.SDK_INT
>=Build.VERSION\u CODES.HONEYCOMB?
Data.DISPLAY\u名称:
Data.DISPLAY\u名称
};
/*
*定义包含布局视图的资源ID的数组
*获取游标列内容的。id在中预定义
*Android框架,因此它的开头是“Android.R.id”
*/
私有最终静态int[]到_id={
android.R.id.text1
};
//定义全局可变变量
//定义ListView对象
ListView mContactsList;
//为用户选择的联系人定义变量
//联系人的_ID值
长触觉;
//联系人的查找键
字符串mContactKey;
//所选联系人的内容URI
Uri-mContactUri;
//_ID列的列索引
私有静态最终int联系人ID索引=0;
//查找键列的列索引
私有静态最终整型查找\密钥\索引=1;
//定义文本表达式
私有静态最终字符串mime_type=“vnd.android.cursor.item/vnd.com.whatsapp.profile”;
私有静态最终字符串选择=
Data.MIMETYPE+“=”+mime_type+“”;
//为搜索字符串定义一个变量
私有字符串mSearchString=“Gourav”;
//定义数组以保存替换?
私有字符串[]mSelectionArgs={mSearchString};
私有静态最终字符串[]投影=
{
联系人。\u ID,
Contacts.LOOKUP_键,
Data.DISPLAY_NAME,
Build.VERSION.SDK_INT
>=Build.VERSION\u CODES.HONEYCOMB?
Data.MIMETYPE:
Data.MIMETYPE
};
//将结果游标绑定到ListView的适配器
私人SimpleCursorAdapter mCursorAdapter;
公共占位符片段(){
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment_main,容器,
假);
返回rootView;
}
@凌驾
已创建ActivityState上的公共无效(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0,null,this);
//从父活动的视图列表中获取ListView
mContactsList=(ListView)getActivity().findViewById(R.id.list);
//获取游标适配器
mCursorAdapter=新的SimpleCursorAdapter(
getActivity(),
R.布局。联系人列表,
无效的
从\u列到\u ID,
0);
//设置ListView的适配器
mContactsList.setAdapter(mCursorAdapter);
}
@凌驾
public void onItemClick(AdapterView父视图、视图、整型位置、,
长id){
//TODO自动生成的方法存根
//获取光标
Cursor Cursor=(Cursor)parent.getAdapter().getItem(位置);
//移动到所选联系人
光标。移动位置(位置);
//获取_ID值
mContactId=cursor.getLong(联系人ID索引);
//获取选定的查找键
mContactKey=cursor.getString(查找键索引);
//创建联系人的内容Uri
mContactUri=Contacts.getLookupUri(mContactId,mContactKey);
/*
*您可以使用mContactUri作为用于检索的内容URI
*联系人的详细信息。
*/
}
@凌驾
public android.support.v4.content.Loader onCreateLoader(
int arg0,Bundle arg1){
//TODO自动生成的方法存根
/*
*将搜索字符串转换为模式和
*将其存储在选择数组中
*/
游标装入器游标=null;
mSelectionArgs[0]=“%”+mSearchString+“%”;
Log.d(“在创建加载器上”,“O
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);

    }


}

}
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();
}