从Android通讯录中获取名字和姓氏,可以通过ContentResolver查询ContactsContract.Contacts表来实现。以下是具体的步骤和示例代码:
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_READ_CONTACTS = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
readContacts();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts();
}
}
}
private void readContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String firstName = "";
String lastName = "";
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))},
null);
if (phoneCursor != null && phoneCursor.moveToFirst()) {
do {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// 这里可以根据需要处理电话号码
} while (phoneCursor.moveToNext());
phoneCursor.close();
}
String[] nameParts = displayName.split(" ");
if (nameParts.length > 0) {
firstName = nameParts[0];
}
if (nameParts.length > 1) {
lastName = nameParts[nameParts.length - 1];
}
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
} while (cursor.moveToNext());
cursor.close();
}
}
}
AndroidManifest.xml
中声明了READ_CONTACTS
权限,并在运行时请求权限。AndroidManifest.xml
中声明了READ_CONTACTS
权限,并在运行时请求权限。通过以上步骤和代码示例,你可以从Android通讯录中获取名字和姓氏,并进行相应的处理。
领取专属 10元无门槛券
手把手带您无忧上云