【问题标题】:How to get all the contacts for a given name prefix in android如何在android中获取给定名称前缀的所有联系人
【发布时间】:2013-12-16 05:27:50
【问题描述】:

我目前正在开发一个打算根据用户语音输入呼叫用户的安卓应用程序。那是用户说出名字(即“约翰”)的时候。我想从我的联系人列表中检索所有联系人,其中包含该姓名和他们的联系号码(即“John Mavel - +94715295296,John Cena - +94715295286,Marine Jone - +94715294568,Josh John Samuwel - +94715297895。等”) .如果只有一个联系人使用该名称,我想直接拨打电话而不提供任何建议。到目前为止,我已经实现了一个代码来调用给定的硬编码名称。它需要语音输入。

            package com.chamika_kasun.voicerecognitionapp;

            import java.util.ArrayList;
            import java.util.List;
            //import java.util.List;

            import android.net.Uri;
            import android.os.Bundle;
            import android.provider.ContactsContract;
            import android.provider.ContactsContract.CommonDataKinds.Phone;
            import android.app.Activity;
            import android.content.ContentResolver;
            import android.content.Intent;
            import android.content.pm.PackageManager;
            import android.database.Cursor;
            //import android.content.pm.PackageManager;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.widget.ArrayAdapter;
            import android.widget.Button;
            import android.widget.ListView;
            import android.widget.Toast;
            import android.speech.RecognizerIntent;
            import android.content.pm.ResolveInfo;

            public class MakeCall extends Activity implements OnClickListener {

                public ListView mList;
                public Button speakButton;

                public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

                @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.make_call);

                    speakButton = (Button) findViewById(R.id.btn_speak);
                    speakButton.setOnClickListener(this);

                    voiceinputbuttons();

                    // Check to see if a recognition activity is present
                    // if running on AVD virtual device it will give this message. The mic
                    // required only works on an actual android device
                      // Disable button if no recognition service is present
                    PackageManager pm = getPackageManager();
                    List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
                    if (activities.size() == 0)
                    {
                        speakButton.setEnabled(false);
                        speakButton.setText("Recognizer not present");
                    }

                }


                public void voiceinputbuttons() {
                    speakButton = (Button) findViewById(R.id.btn_speak);
                    mList = (ListView) findViewById(R.id.list);
                }

                public void startVoiceRecognitionActivity() {

                    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Speech recognition demo");
                    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

                }

                public void onClick(View v) {

                    startVoiceRecognitionActivity();

                }

                @Override
                public void onActivityResult(int requestCode, int resultCode, Intent data) {
                    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
                        // Fill the list view with the strings the recognizer thought it
                        // could have heard
                        ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                        mList.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, matches));

                        //if (matches.contains("vidudaya")) {

                            String name = matches.toString();
                            String number = "";


                            Toast.makeText(this, "Name : "+name,Toast.LENGTH_SHORT).show();

                            ContentResolver cr = getContentResolver();
                            Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,"DISPLAY_NAME = '" + name + "'", null, null);
                            if (cursor.moveToFirst()) {
                                String contactId =
                                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                                //
                                //  Get all phone numbers.
                                //
                                Cursor phones = cr.query(Phone.CONTENT_URI, null,
                                    Phone.CONTACT_ID + " = " + contactId, null, null);
                                while (phones.moveToNext()) {
                                   number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
            //                      int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
            //                      switch (type) {
            //                          case Phone.TYPE_HOME:
            //                              // do something with the Home number here...
            //                              break;
            //                          case Phone.TYPE_MOBILE:
            //                              // do something with the Mobile number here...
            //                              break;
            //                          case Phone.TYPE_WORK:
            //                              // do something with the Work number here...
            //                              break;
            //                          }

                                    Toast.makeText(this, "My Mobile Number : "+number,Toast.LENGTH_SHORT).show();

                                }
                                phones.close();
                               }
                               cursor.close();

                                String url = "tel:"+number;
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
                                startActivity(intent);

                        //}


                        super.onActivityResult(requestCode, resultCode, data);
                    }
                }

            }

【问题讨论】:

    标签: android android-contacts


    【解决方案1】:

    此代码根据联系人姓名检索联系人:

    Cursor contactLookupCursor =
            getContentResolver().query(
                    Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                            Uri.encode("Rohan")),
                    new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER},
                    null,
                    null,
                    null);
    
    try {
        while (contactLookupCursor.moveToNext()) {
            contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
            contactNumber = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.NUMBER));
        }
    } finally {
        contactLookupCursor.close();
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      好的,试试这个,然后告诉我会发生什么,

      看看 ContactsContract.CommonDataKinds.StructuredName 班级。您可以在那里找到您要查找的所有列。

       String whereName = ContactsContract.Data.MIMETYPE + " = ?";
          String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
          Cursor nameCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
          while (nameCur.moveToNext()) {
              String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
              String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
              String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
          }
          nameCur.close();
      

      参考, Look at this question How to get the firstname and lastname from android contacts?

      Working-With-Android-Contacts

      【讨论】:

        【解决方案3】:

        您可以使用此代码查找联系人

        String searchName = "john";
        String name, number;
        String columns[] = new String[] { People.NAME, People.NUMBER };
        Uri mContacts = People.CONTENT_URI;
        Cursor cur= getContentResolver().query(mContacts, columns, null,null, null);
        if (cur.moveToFirst()) {
            do {
            name = cur.getString(cur.getColumnIndex(People.NAME));
            number = cur.getString(cur.getColumnIndex(People.NUMBER));
        
            if((number!=null) && (name.toLowerCase().contains(searchName.toLowerCase()))){
             Toast.makeText(this, name, Toast.LENGTH_LONG).show(); 
        //              Add Contact to Search array.
                }
           } while (cur.moveToNext());
        }
        

        【讨论】:

          【解决方案4】:

          我做过一次,有点冗长但很容易......

          1. 我根据姓名将联系人存储在字符串中。
          2. 为我需要的人搜索字符串。

           String contacts = new String();
          
                  if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                      if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_CONTACTS)) {
                          ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
                      } else {
                          ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
                      }
                      getContactDetails();
                  } else {
          
                      int flag = 1;
                      ContentResolver cr = getContentResolver();
                      Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                              null, null, null, null);
                      if ((cur != null ? cur.getCount() : 0) > 0) {
                          while (cur != null && cur.moveToNext()) {
                              String id = cur.getString(
                                      cur.getColumnIndex(ContactsContract.Contacts._ID));
                              String name = cur.getString(cur.getColumnIndex(
                                      ContactsContract.Contacts.DISPLAY_NAME));
          
                              if (cur.getInt(cur.getColumnIndex(
                                      ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                                  Cursor pCur = cr.query(
                                          ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                          null,
                                          ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                          new String[]{id}, null);
                                  while (pCur.moveToNext()) {
                                      String phoneNo = pCur.getString(pCur.getColumnIndex(
                                              ContactsContract.CommonDataKinds.Phone.NUMBER));
                                      contacts= contacts+ name + ":" + phoneNo + "<br>";
                                      flag++;
                                  }
                                  pCur.close();
                              }
                          }
                      }
                      if (cur != null) {
                          cur.close();
                      }
                  }
                  return contacts;

          这个函数返回一个字符串值...

          【讨论】:

            猜你喜欢
            • 2012-09-15
            • 2018-01-25
            • 1970-01-01
            • 2011-05-19
            • 1970-01-01
            • 2021-06-25
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多