Xamarin访问联系簿以获取信息

时间:2017-02-13 12:27:35

标签: android xamarin contact

我正在研究Android(Xamarin)上的应用程序,这就是我想要做的事情:

当用户点击按钮时,他可以选择联系人簿中的联系人,然后将姓名和电话号码写入2 editText(姓名和电话号码)

如何访问联系簿并获取所需数据?

这是我现在的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Preferences;
using Android.Provider;

namespace EmergencyCall
{
    [Activity(Label = "AddContact")]
    public class AddContact : Activity
    {
        EditText nom;
        EditText numero;
        Button save;
        Button addFromReper;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.add_Contact);
            nom = FindViewById<EditText>(Resource.Id.nomPersonne);
            numero = FindViewById<EditText>(Resource.Id.NumeroTel);
            save = FindViewById<Button>(Resource.Id.saveNewContact);
            addFromReper = FindViewById<Button>(Resource.Id.addFromRepert);
            ISharedPreferences prefs;
            ISharedPreferencesEditor editor;
            prefs = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
            editor = prefs.Edit();


            save.Click += delegate
            {
                ISet<String> names = new HashSet<String>    (prefs.GetStringSet("NomsContacts", new HashSet<String>()));
                names.Add(nom.Text);
                editor.PutStringSet("NomsContacts", names);
                editor.PutString(nom.Text, numero.Text);
                editor.Apply();
                StartActivity(typeof(ModifyContacts));
            };

            addFromReper.Click += delegate
            {
                Intent intent = new Intent(Intent.ActionPick,     Contacts.ContentUri);
                StartActivityForResult(intent, 1);
            };

        }

    }
}

谢谢:)

1 个答案:

答案 0 :(得分:0)

如果有人需要,我终于找到了如何做到这一点:

 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == 1)
        {

            if (resultCode == Result.Ok)
            {
                Android.Net.Uri contactData = data.Data;
                ICursor cursor = ContentResolver.Query(contactData, null, null, null, null);

                cursor.MoveToFirst();
                string name = cursor.GetString(cursor.GetColumnIndexOrThrow(ContactsContract.Contacts.InterfaceConsts.DisplayName));
                string number = cursor.GetString(cursor.GetColumnIndexOrThrow(Android.Provider.ContactsContract.CommonDataKinds.Phone.Number));

                nom.Text=name;
                numero.Text = number;

            }
        }