packagecom.aimee.android.play.addcontact;importandroid.Manifest;importandroid.content.ContentResolver;importandroid.content.ContentValues;importandroid.database.Cursor;importandroid.net.Uri;importandroid.os.Bundle;importandroid.text.TextUtils;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.Toast;public class MainActivity extendsBaseActivity {private static final String TAG = "MainActivity";privateEditText mEtname;privateEditText mEtmail;privateEditText mEtphone;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
performCodeWithPermission("插入联系人信息", newPermissionCallback() {
@Overridepublic voidhasPermission() {
}
@Overridepublic voidnoPermission() {
}
}, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS);
mEtname=findViewById(R.id.et_name);
mEtmail=findViewById(R.id.et_email);
mEtphone=(EditText) findViewById(R.id.et_phone);
}/*** 添加联系人信息
*@paramview*/
public voidaddContact(View view) {//1.判断是否为空
String name =mEtname.getText().toString().trim();
String email=mEtmail.getText().toString().trim();
String phone=mEtphone.getText().toString().trim();if(TextUtils.isEmpty(name)){
Toast.makeText(this,"姓名不能为空",Toast.LENGTH_SHORT).show();return;
}//2.在raw_contact表里面添加联系人id
ContentResolver resolver =getContentResolver();
Uri uri= Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri= Uri.parse("content://com.android.contacts/data");
Cursor cursor= resolver.query(uri, null, null, null, null, null);int new_id = cursor.getCount() + 1;
ContentValues values= newContentValues();
resolver.insert(uri,values);//3.在data表里面添加联系人数据
ContentValues namevalues = newContentValues();
namevalues.put("raw_contact_id",new_id);
namevalues.put("data1",name);
namevalues.put("mimetype","vnd.android.cursor.item/name");
resolver.insert(dataUri,namevalues);
ContentValues phonevalues= newContentValues();
phonevalues.put("raw_contact_id",new_id);
phonevalues.put("data1",phone);
phonevalues.put("mimetype","vnd.android.cursor.item/phone_v2");
resolver.insert(dataUri,phonevalues);
ContentValues emailvalues= newContentValues();
emailvalues.put("raw_contact_id",new_id);
emailvalues.put("data1",email);
emailvalues.put("mimetype","vnd.android.cursor.item/email_v2");
resolver.insert(dataUri,emailvalues);
Toast.makeText(this,"添加信息成功",Toast.LENGTH_SHORT).show();
}
}