Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Redth/1449755 to your computer and use it in GitHub Desktop.
Save Redth/1449755 to your computer and use it in GitHub Desktop.
Send SMS to Contact using Xamarin.Mobile in Mono for Android!
void button_Click(object sender, EventArgs e)
{
//Create a new intent for choosing a contact
var contactPickerIntent = new Intent(Intent.ActionPick,
Android.Provider.ContactsContract.Contacts.ContentUri);
//Start the contact picker expecting a result
// with the resultCode '101'
StartActivityForResult(contactPickerIntent, 101);
}
public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
//See if we are handling the contact picker request code
// and that the result code is ok!
if (requestCode == 101 && resultCode == Result.Ok)
{
//Ensure we have data returned
if (data == null || data.Data == null)
return;
//Xamarin.Mobile code here :)
var addressBook = new Xamarin.Contacts.AddressBook(this);
//Note: This is important
addressBook.PreferContactAggregation = true;
//Load the contact via the android contact id
// in the last segment of the Uri returned by the
// android contact picker
var contact = addressBook.Load(data.Data.LastPathSegment);
//Use linq to find a mobile number
var mobile = (from p in contact.Phones where
p.Type == Xamarin.Contacts.PhoneType.Mobile
select p.Number).FirstOrDefault();
//See if the contact has a mobile number
if (string.IsNullOrEmpty(mobile))
{
Toast.MakeText(this, "No Mobile Number for contact!",
ToastLength.Short).Show();
return;
}
//Send SMS!
var smsMgr = Android.Telephony.SmsManager.Default;
smsMgr.SendTextMessage(mobile, null, "Hello World!", null, null);
}
}
@adilkhali
Copy link

thanks , that was helpful ;)

@fionariza
Copy link

thank you very much!!!!

@rpcob
Copy link

rpcob commented May 14, 2016

The following error occurs for linq statement: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object

@ZeeshanHaiderDMT
Copy link

it is not work sir.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment