请帮我写一个Android Studio ContentProvide实验程序,要求使用系统提供的ContentProvider。 实验要求: (1)读取手机联系人 (2)查询指定电话的联系人信息。 (3)添加一个新的联系人。
时间: 2024-03-11 21:45:06 浏览: 172
好的,以下是一个简单的Android Studio ContentProvider实验程序,可以满足您的要求。请注意,这个程序使用了系统提供的ContactsContract内容提供器来访问联系人信息。
首先,在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
```
然后,在MainActivity.java文件中定义以下代码:
```java
import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int READ_CONTACTS_PERMISSIONS_REQUEST = 1;
private static final int WRITE_CONTACTS_PERMISSIONS_REQUEST = 2;
@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},
READ_CONTACTS_PERMISSIONS_REQUEST);
} else {
readContacts();
}
// 请求写入联系人权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_CONTACTS},
WRITE_CONTACTS_PERMISSIONS_REQUEST);
} else {
addContact();
}
}
// 读取联系人信息
private void readContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(Contacts._ID));
// 查询联系人的电话号码
Cursor phoneCursor = contentResolver.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = ?", new String[]{id}, null);
if (phoneCursor != null && phoneCursor.getCount() > 0) {
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER));
Log.d("Contact", name + " " + phoneNumber);
}
}
if (phoneCursor != null) {
phoneCursor.close();
}
}
}
if (cursor != null) {
cursor.close();
}
}
// 查询指定电话的联系人信息
private void queryContactByPhoneNumber(String phoneNumber) {
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = contentResolver.query(uri, new String[]{Phone.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToNext();
String name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
Log.d("Contact", "Phone number " + phoneNumber + " belongs to " + name);
} else {
Log.d("Contact", "No contact found for phone number " + phoneNumber);
}
if (cursor != null) {
cursor.close();
}
}
// 添加一个新的联系人
private void addContact() {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
// 添加一个新的RawContact
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
// 添加联系人姓名
ops.add(ContentProviderOperation.newInsert(Contacts.CONTENT_URI)
.withValue(Contacts.DISPLAY_NAME, "Test Contact")
.build());
// 添加联系人电话号码
ops.add(ContentProviderOperation.newInsert(Phone.CONTENT_URI)
.withValueBackReference(Phone.RAW_CONTACT_ID, 0)
.withValue(Phone.NUMBER, "+8613800000000")
.withValue(Phone.TYPE, Phone.TYPE_MOBILE)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(MainActivity.this, "Contact added successfully", Toast.LENGTH_SHORT).show();
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_CONTACTS_PERMISSIONS_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts();
}
break;
case WRITE_CONTACTS_PERMISSIONS_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
addContact();
}
break;
}
}
}
```
这个程序中,readContacts()方法用于读取所有联系人信息,并且查询每个联系人的电话号码。queryContactByPhoneNumber()方法用于查询指定电话号码的联系人信息。addContact()方法用于添加一个新的联系人,其中包括联系人姓名和电话号码。
请注意,这个程序只是一个简单的示例,实际的应用程序可能需要更多的错误处理和用户提示。
阅读全文