每做一个项目都会有收获,前提是要在这个项目上付出努力的!
好吧,现在讲一下:怎么通过调用系统通讯录,当你点击联系人姓名时,跳转到向其发送短信的页面<收件人是被点中的联系人,短信已自动编辑>。
看看图片效果:
下面看一下详细代码:
Uri result = data.getData();
String phoneName = getPhoneContacts(result);
Log.d("phone", "---------->phoneName=="+contactName);
String smsContent="发给你一个时尚园APP的注册邀请码,他们家的东西很有品。" +
""+"\n"+strInviteCode+"(时尚园 APP下载地址http://t.so)";
sendSMS(phoneName,smsContent);
/**
* 获取联系人手机号码
* @param contactId
* @return
*/
@SuppressWarnings("deprecation")
private String getPhoneContacts(Uri contactId) {
Cursor cursor = null;
String phoneName = "";//联系人姓名
String phoneNum = "";//联系人电话号码
String phoneID = "";//联系人ID
try {
// Uri uri = People.CONTENT_URI;
cursor=getContentResolver().query(contactId, null, null, null, null);
if (cursor.moveToNext()) {
phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
phoneID=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Log.d("phone", "phoneName&&phoneNumber=="+phoneName+"-----"+phoneID);
Cursor c=getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID+"="+phoneID, null, null);
while(c.moveToNext()){
phoneNum=c.getString(c.getColumnIndex("data1"));
Log.d("phone", "phoneNumber=="+phoneNum);
}
} else {
Toast.makeText(this, "找不到该联系人",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return phoneNum;
}
/**
* 发送短信
*
* @param smsBody
*/
private void sendSMS(String phoneNum, String smsBody) {
Log.d("phone", "sendSMS(String phoneNum, String smsBody)=="+phoneNum);
Uri smsToUri = Uri.parse("smsto:"+phoneNum);
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", smsBody);
startActivity(intent);
// Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", phoneNum, null));
// mmsintent.putExtra("sms_body", smsBody);
// startActivity(mmsintent);
/* 建立SmsManager对象 */
// SmsManager smsManager = SmsManager.getDefault();
// smsManager.sendTextMessage(phoneNum, null, smsBody, null, null);
}